hunix.cpp 660 B

123456789101112131415161718192021222324252627282930313233343536373839
  1. #ifdef __unix__
  2. #include "hunix.h"
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <fcntl.h>
  9. #include <errno.h>
  10. void daemonize(){
  11. pid_t pid = fork();
  12. if (pid < 0){
  13. printf("fork error: %d", errno);
  14. return;
  15. }
  16. if (pid > 0){
  17. // exit parent process
  18. exit(0);
  19. }
  20. // child process become process leader
  21. setsid();
  22. // set fd
  23. int fd;
  24. if ((fd = open("/dev/null", O_RDWR, 0)) != -1){
  25. dup2(fd, STDIN_FILENO);
  26. dup2(fd, STDOUT_FILENO);
  27. dup2(fd, STDERR_FILENO);
  28. if (fd > STDERR_FILENO)
  29. close(fd);
  30. }
  31. }
  32. #endif // __unix__