[lkml]   [2006]   [Nov]   [20]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
Messages in this thread
SubjectRe: RFC: implement daemon() in the kernel
Simon Richter wrote:
> - daemonize a process
> There is a function called daemon() that does this; its behaviour is
> roughly defined by (modulo error handling)
> int daemon(int nochdir, int noclose)
> {
> if(!nochdir)
> chdir("/");
> if(!noclose)
> {
> int fd = open("/dev/null", O_RDWR);
> dup2(fd, 0);
> dup2(fd, 1);
> dup2(fd, 2);
> close(fd);
> }
> if(fork() > 0)

... that should be if (fork() == 0) ...

> _exit(0);

> }

> Since it calls _exit() right after fork() returns (so daemon() never
> returns to the calling process except in case of an error) it would be
> possible to implement this on MMUless machines if the last two lines
> could happen in the kernel.

You could do this quite easily with clone() and a small assembly wrapper.

The assembly wrapper needs to do the last two lines without touching the
stack in the parent. That is usually quite trivial, even on
register-starved architectures; for example, on i386 it would look like
(ignoring vsyscalls for the moment, which are only an optimization anyway).

pushl %ebx
movl $__NR_clone, %eax
movl $CLONE_VM|SIGCHLD, %ebx
xorl %ecx, %ecx
int $0x80
cmpl $-4096, %eax
ja 1f
andl %eax, %eax
je 2f
# Parent process, must _exit(0)
xorl %ebx, %ebx
movl $__NR_exit, %eax
int $0x80
# _exit() should never return
1: # Error on fork(), set errno and return -1
negl %eax
movl %eax, errno # Or TLS equivalent
orl $-1, %eax
2: # Child process jumps here with %eax == 0 already
popl %ebx

To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to
More majordomo info at
Please read the FAQ at

 \ /
  Last update: 2006-11-21 01:41    [W:0.072 / U:2.460 seconds]
©2003-2020 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site