Difference between revisions of "Daemonise.c"

From Organic Design wiki
(make nice ps name)
m
Line 1: Line 1:
// Convert running program into a system daemon
+
// Set name as seen in ps list
strcpy(*argv, sprintf(*argv,"%s (peerd:%s)",peer,port));
+
sprintf(*argv,"%s (peerd:%s)",peer,port);
 +
 
 +
// Fork so parent can exit and return control to what invoked it
 
pid_t pid = fork();
 
pid_t pid = fork();
 
if (pid > 0) exit(EXIT_SUCCESS);
 
if (pid > 0) exit(EXIT_SUCCESS);
 
if (pid < 0) exit(logErr("First fork() failed!"));
 
if (pid < 0) exit(logErr("First fork() failed!"));
 +
 +
// Become a new session leader with no controlling term
 
if (setsid() < 0) exit(logErr("setsid() failed!"));
 
if (setsid() < 0) exit(logErr("setsid() failed!"));
 +
 +
// Fork again to be a non-session-leader which can't gain a controlling term
 
pid = fork();
 
pid = fork();
 
if (pid > 0) exit(EXIT_SUCCESS);
 
if (pid > 0) exit(EXIT_SUCCESS);
 
if (pid < 0) exit(logErr("Second fork() failed!"));
 
if (pid < 0) exit(logErr("Second fork() failed!"));
chdir("/");
+
 
umask(0);
+
chdir("/"); // Don't keep any dir in use
 +
umask(0);   // Don't inherit any file perms mask
 
//close(STDIN_FILENO);
 
//close(STDIN_FILENO);
 
//close(STDOUT_FILENO);
 
//close(STDOUT_FILENO);
 
//close(STDERR_FILENO);
 
//close(STDERR_FILENO);

Revision as of 23:45, 21 July 2006

// Set name as seen in ps list sprintf(*argv,"%s (peerd:%s)",peer,port);

// Fork so parent can exit and return control to what invoked it pid_t pid = fork(); if (pid > 0) exit(EXIT_SUCCESS); if (pid < 0) exit(logErr("First fork() failed!"));

// Become a new session leader with no controlling term if (setsid() < 0) exit(logErr("setsid() failed!"));

// Fork again to be a non-session-leader which can't gain a controlling term pid = fork(); if (pid > 0) exit(EXIT_SUCCESS); if (pid < 0) exit(logErr("Second fork() failed!"));

chdir("/"); // Don't keep any dir in use umask(0); // Don't inherit any file perms mask //close(STDIN_FILENO); //close(STDOUT_FILENO); //close(STDERR_FILENO);