Difference between revisions of "Daemonise.c"

From Organic Design wiki
(chdir to /home/peerd)
m
Line 1: Line 1:
// Fork so parent can exit and return control to what invoked it
+
void peerd_init() {
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
+
// Fork so parent can exit and return control to what invoked it
if (setsid() < 0) exit(logErr("setsid() failed!"));
+
pid_t pid = fork();
 +
if (pid > 0) exit(EXIT_SUCCESS);
 +
if (pid < 0) exit(logErr("First fork() failed!"));
  
// Fork again to be a non-session-leader which can't gain a controlling term
+
// Become a new session leader with no controlling term
pid = fork();
+
if (setsid() < 0) exit(logErr("setsid() failed!"));
if (pid > 0) exit(EXIT_SUCCESS);
 
if (pid < 0) exit(logErr("Second fork() failed!"));
 
  
// Should be /home/lc(peer)
+
// Fork again to be a non-session-leader which can't gain a controlling term
chdir("/home/peerd");
+
pid = fork();
 +
if (pid > 0) exit(EXIT_SUCCESS);
 +
if (pid < 0) exit(logErr("Second fork() failed!"));
  
// Don't inherit any file perms mask
+
// Should be /home/lc(peer)
umask(0);
+
chdir("/home/peerd");
  
//close(STDIN_FILENO);
+
// Don't inherit any file perms mask
//close(STDOUT_FILENO);
+
umask(0);
//close(STDERR_FILENO);
+
 
 +
//close(STDIN_FILENO);
 +
//close(STDOUT_FILENO);
 +
//close(STDERR_FILENO);
 +
 
 +
}

Revision as of 05:30, 28 July 2006

void peerd_init() {

// 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!"));

// Should be /home/lc(peer) chdir("/home/peerd");

// Don't inherit any file perms mask umask(0);

//close(STDIN_FILENO); //close(STDOUT_FILENO); //close(STDERR_FILENO);

}