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