run.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <ccan/daemonize/daemonize.h>
  2. #include <ccan/daemonize/daemonize.c>
  3. #include <ccan/tap/tap.h>
  4. #include <stdlib.h>
  5. #include <unistd.h>
  6. #include <err.h>
  7. #include <errno.h>
  8. #include <string.h>
  9. struct child_data {
  10. pid_t pid;
  11. pid_t ppid;
  12. bool in_root_dir;
  13. int read_from_stdin, write_to_stdout, write_to_stderr;
  14. };
  15. int main(int argc, char *argv[])
  16. {
  17. int fds[2];
  18. struct child_data daemonized;
  19. pid_t pid;
  20. plan_tests(6);
  21. if (pipe(fds) != 0)
  22. err(1, "Failed pipe");
  23. /* Since daemonize forks and parent exits, we need to fork
  24. * that parent. */
  25. pid = fork();
  26. if (pid == -1)
  27. err(1, "Failed fork");
  28. if (pid == 0) {
  29. char buffer[2];
  30. pid = getpid();
  31. daemonize();
  32. /* Keep valgrind happy about uninitialized bytes. */
  33. memset(&daemonized, 0, sizeof(daemonized));
  34. daemonized.pid = getpid();
  35. daemonized.in_root_dir = (getcwd(buffer, 2) != NULL);
  36. daemonized.read_from_stdin
  37. = read(STDIN_FILENO, buffer, 1) == -1 ? errno : 0;
  38. daemonized.write_to_stdout
  39. = write(STDOUT_FILENO, buffer, 1) == -1 ? errno : 0;
  40. if (write(STDERR_FILENO, buffer, 1) != 1) {
  41. daemonized.write_to_stderr = errno;
  42. if (daemonized.write_to_stderr == 0)
  43. daemonized.write_to_stderr = -1;
  44. } else
  45. daemonized.write_to_stderr = 0;
  46. /* Make sure parent exits. */
  47. while (getppid() == pid)
  48. sleep(1);
  49. daemonized.ppid = getppid();
  50. if (write(fds[1], &daemonized, sizeof(daemonized))
  51. != sizeof(daemonized))
  52. exit(1);
  53. exit(0);
  54. }
  55. if (read(fds[0], &daemonized, sizeof(daemonized)) != sizeof(daemonized))
  56. err(1, "Failed read");
  57. ok1(daemonized.pid != pid);
  58. ok1(daemonized.ppid == 1);
  59. ok1(daemonized.in_root_dir);
  60. ok1(daemonized.read_from_stdin == EBADF);
  61. ok1(daemonized.write_to_stdout == EBADF);
  62. ok1(daemonized.write_to_stderr == 0);
  63. return exit_status();
  64. }