Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to make a process daemon
    primarykey
    data
    text
    <p>I am trying to understand how can I make my program a daemon.So some things which I came across are In general, a program performs the following steps to become a daemon: </p> <ol> <li>Call <code>fork( )</code>. </li> <li><p>In the parent, call <code>exit( )</code>. This ensures that the original parent (the daemon's grandparent) is satisfied that its child terminated, that the daemon's parent is no longer running, and that the daemon is not a process group leader. This last point is a requirement for the successful completion of the next step. </p></li> <li><p>Call <code>setsid( )</code>, giving the daemon a new process group and session, both of which have it as leader. This also ensures that the process has no associated controlling terminal (as the process just created a new session, and will not assign one).</p></li> <li><p>Change the working directory to the root directory via <code>chdir( )</code>. This is done because the inherited working directory can be anywhere on the filesystem. Daemons tend to run for the duration of the system's uptime, and you don't want to keep some random directory open, and thus prevent an administrator from unmounting the filesystem containing that directory.</p></li> <li><p>Close all file descriptors. </p></li> <li>Open file descriptors 0, 1, and 2 (standard in, standard out, and standard error) and redirect them to <code>/dev/null</code>.</li> </ol> <pre><code>#include &lt;sys/types.h&gt; #include &lt;sys/stat.h&gt; #include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; #include &lt;fcntl.h&gt; #include &lt;unistd.h&gt; #include &lt;linux/fs.h&gt; int main (void) { pid_t pid; int i; /* create new process */ pid = fork ( ); if (pid == -1) return -1; else if (pid != 0) exit (EXIT_SUCCESS); /* create new session and process group */ if (setsid ( ) == -1) return -1; /* set the working directory to the root directory */ if (chdir ("/") == -1) return -1; /* close all open files--NR_OPEN is overkill, but works */ for (i = 0; i &lt; NR_OPEN; i++) close (i); /* redirect fd's 0,1,2 to /dev/null */ open ("/dev/null", O_RDWR); /* stdin */ dup (0); /* stdout */ dup (0); /* stderror */ /* do its daemon thing... */ return 0; }</code></pre> <p>Can some one give me a link to existing source code of some program like Apache so that I can understand this process in more depth.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload