run.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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. daemonized.write_to_stderr
  41. = write(STDERR_FILENO, buffer, 1) == -1 ? errno : 0;
  42. /* Make sure parent exits. */
  43. while (getppid() == pid)
  44. sleep(1);
  45. daemonized.ppid = getppid();
  46. if (write(fds[1], &daemonized, sizeof(daemonized))
  47. != sizeof(daemonized))
  48. exit(1);
  49. exit(0);
  50. }
  51. if (read(fds[0], &daemonized, sizeof(daemonized)) != sizeof(daemonized))
  52. err(1, "Failed read");
  53. ok1(daemonized.pid != pid);
  54. ok1(daemonized.ppid == 1);
  55. ok1(daemonized.in_root_dir);
  56. ok1(daemonized.read_from_stdin == EBADF);
  57. ok1(daemonized.write_to_stdout == EBADF);
  58. ok1(daemonized.write_to_stderr == EBADF);
  59. return exit_status();
  60. }