Linux development

From HoerupWiki
Revision as of 00:12, 17 February 2007 by 192.168.10.10 (talk) (Kode)
Jump to: navigation, search

Denne side skal ses som et linux modstykke til MFC siden.

Application framework og GUI

Skal du lave noget C++ til linux er der mange toolkits at vælge i mellem. Men du vil sikkert få mest success med enten wxWidgets eller Qt.

Tråde

Sockets

Daemon

Hvis at man laver et server program til linux, vil man som regel gerne at processen kører i baggrunden - her er et eksempel på hvordan at det kan laves:

Kode

#define LOCKFILE "/tmp/myapp.lock"

#define daemon_shutdown(x) exit(x)

void log_message(const char *);
 
void signal_handler(int sig)
{
	switch(sig) {
		case SIGHUP:
			log_message("hangup signal catched");
			break;
		case SIGTERM:
			log_message("terminate signal catched...exiting");
			unlink(LOCKFILE);
			daemon_shutdown(0);
			break;
	}
}


void daemonize()
{	
	int i, lfp;
	char str[10];
	
	if (getppid() == 1) /* already a daemon */
		return;
		
	i=fork();
	
	if (i<0) /* fork error */
		daemon_shutdown(FORK_ERROR);
	if (i>0) /* parent exits */
		daemon_shutdown(0);
	/* child daemon continues */
	
	setsid(); /* obtain a new process group */
	
	for (i=getdtablesize(); i>=0; --i)
		close(i); /*close all descriptors*/
		
	i=open("/dev/null", O_RDWR); /* handle std. io */
	dup(i);
	dup(i);
	
	umask(027); /* set newly created file permissions */
	
	chdir("/tmp"); /* change running directory*/
	
	//attempt to create lockfile and put a file-lock on it
	lfp=open(LOCKFILE, O_RDWR|O_CREAT, 0640);
	if (lfp<0) /* can not open */
		daemon_shutdown(CANT_OPEN_LOCK);
	if (lockf(lfp,F_TLOCK,0) < 0) /* can not lock */
		daemon_shutdown(ALREADY_LOCKED);
	
	/* first instance continues */
	sprintf(str, "%d\n", getpid() ); /* record pid to lockfile */
	write(lfp, str, strlen(str) );
	signal(SIGCHLD, SIG_IGN); /* ignore child */
	signal(SIGTSTP, SIG_IGN); /* ignore tty signals */
	signal(SIGTTOU, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGHUP, signal_handler); /* catch hangup signal */
	signal(SIGTERM, signal_handler); /* catch kill signal */	

	/*this program is now a daemon*/
}