1
0

daemon.c 565 B

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