Paul Brown wrote:

> I am just about fnished writing a daemon, and would like to know how i
> can make the program fork into
> the background automatically..

The attached program contains suitable startup code for a daemon. You
only asked for step 1, but steps 2-5 are generally considered
necessary.

-- 
Glynn Clements <[EMAIL PROTECTED]>


#include <stdio.h>      /* for perror */
#include <unistd.h>     /* for fork, setsid, chdir, sysconf, close */
#include <sys/stat.h>   /* for umask */

int main(void)
{
        int n, i;

        /* step 1: fork() a child process and exit */

        switch (fork())
        {
        case -1:        /* error */
                perror("fork");
                return 1;

        case 0:         /* child */
                break;

        default:        /* parent*/
                return 0;
        }

        /* step 2: establish a new session */

        if (setsid() < 0)
        {
                perror("setsid");
                return 1;
        }

        /* step 3: set the cwd */

        if (chdir("/") < 0)
        {
                perror("chdir");
                return 1;
        }

        /* step 4: reset the umask */

        umask(0);

        /* step 5: close open descriptors */

        n = sysconf(_SC_OPEN_MAX);
        if (n < 0)
                n = 256;

        for (i = 0; i < n; i++)
                if (close(i) < 0)
                        perror("close");

        /* everything else goes here */

        return 0;
}

Reply via email to