[uClinux-dev] Daemonize a process

Stuart MacDonald stuartm at connecttech.com
Thu Mar 13 10:38:59 EST 2003


From: "Roope Anttinen" <roope.anttinen at indagon.com>
> Try something like this. Fairly standard stuff but I haven't tried this
> is uClinux so it might need some modifications.

As I mentioned in my original post, this does not work properly.

> int daemonize()
> {
>     int fd;
>     pid_t pid;
>
>     pid = fork();
>
>     switch (pid) {
>     case -1:
>         return -1;
>     case 0:

The child runs, gets to this line and continues with the setsid below.

>         break;
>     default:

The parent is blocked waiting for the child to _exit() or execve(),
and does not reach the line below until that happens. This leaves the
parent process in the D state, and AFAICanTell, also does not detach
the daemon from the controlling tty, meaning that when one logs out,
the process is killed.

>         _exit(pid);
>     }
>
>     if (setsid() == -1)
>         return -1;
>     chdir("/");
>     fd = open(_PATH_DEVNULL, O_RDWR, 0);
>     if (fd != -1) {
>         dup2(fd, STDIN_FILENO);
>         dup2(fd, STDOUT_FILENO);
>         dup2(fd, STDERR_FILENO);
>         if (fd > 2)
>             close(fd);
>     }
>     return 0;
> }

..Stu





More information about the uClinux-dev mailing list