run.c 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. #include <ccan/daemon-with-notify/daemon.h>
  2. #include <ccan/tap/tap.h>
  3. #include <stdlib.h>
  4. #include <unistd.h>
  5. #include <err.h>
  6. #include <errno.h>
  7. #include <string.h>
  8. struct child_data {
  9. pid_t pid;
  10. pid_t ppid;
  11. bool in_root_dir;
  12. int read_from_stdin, write_to_stdout, write_to_stderr;
  13. };
  14. int main(int argc, char *argv[])
  15. {
  16. int fds[2];
  17. struct child_data daemonized;
  18. pid_t pid;
  19. plan_tests(6);
  20. if (pipe(fds) != 0)
  21. err(1, "Failed pipe");
  22. /* Since daemonize forks and parent exits, we need to fork
  23. * that parent. */
  24. pid = fork();
  25. if (pid == -1)
  26. err(1, "Failed fork");
  27. if (pid == 0) {
  28. char buffer[2];
  29. pid = getpid();
  30. daemonize(0, 0, 1);
  31. daemon_is_ready();
  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. }