github.com/afumu/libc@v0.0.6/musl/src/legacy/daemon.c (about)

     1  #define _GNU_SOURCE
     2  #include <fcntl.h>
     3  #include <unistd.h>
     4  
     5  int daemon(int nochdir, int noclose)
     6  {
     7  	if (!nochdir && chdir("/"))
     8  		return -1;
     9  	if (!noclose) {
    10  		int fd, failed = 0;
    11  		if ((fd = open("/dev/null", O_RDWR)) < 0) return -1;
    12  		if (dup2(fd, 0) < 0 || dup2(fd, 1) < 0 || dup2(fd, 2) < 0)
    13  			failed++;
    14  		if (fd > 2) close(fd);
    15  		if (failed) return -1;
    16  	}
    17  
    18  	switch(fork()) {
    19  	case 0: break;
    20  	case -1: return -1;
    21  	default: _exit(0);
    22  	}
    23  
    24  	if (setsid() < 0) return -1;
    25  
    26  	switch(fork()) {
    27  	case 0: break;
    28  	case -1: return -1;
    29  	default: _exit(0);
    30  	}
    31  
    32  	return 0;
    33  }