kill.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <errno.h>
  7. #include <unistd.h>
  8. #include <signal.h>
  9. #include <time.h>
  10. int kill_parent = 0;
  11. int main(int argc, char ** argv)
  12. {
  13. if (argc == 2 && !strcmp("parent", argv[1]))
  14. kill_parent = 1;
  15. int parent_pid = getpid();
  16. pid_t pid = fork();
  17. if (pid < 0) {
  18. printf("failed on fork (%s)\n", strerror(errno));
  19. return -1;
  20. }
  21. if (pid == 0) {
  22. struct timespec rem;
  23. rem.tv_sec = kill_parent ? 1 : 60;
  24. rem.tv_nsec = 0;
  25. printf("[pid=%d|ppid=%d] Going to sleep...\n", getpid(), getppid());
  26. nanosleep(&rem, 0);
  27. if (kill_parent)
  28. kill(parent_pid, SIGKILL);
  29. printf("[pid=%d|ppid=%d] Hello, Dad!\n", getpid(), getppid());
  30. return 0;
  31. }
  32. else {
  33. struct timespec rem;
  34. rem.tv_sec = kill_parent ? 60 : 1;
  35. rem.tv_nsec = 0;
  36. printf("[pid=%d|ppid=%d] Going to sleep...\n", getpid(), getppid());
  37. nanosleep(&rem, 0);
  38. if (!kill_parent)
  39. kill(pid, SIGKILL);
  40. printf("[pid=%d|ppid=%d] Hello, Kid!\n", getpid(), getppid());
  41. return 0;
  42. }
  43. }