kill.c 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include <errno.h>
  5. #include <unistd.h>
  6. #include <signal.h>
  7. #include <time.h>
  8. int kill_parent = 0;
  9. int main(int argc, char ** argv)
  10. {
  11. if (argc == 2 && !strcmp("parent", argv[1]))
  12. kill_parent = 1;
  13. int parent_pid = getpid();
  14. pid_t pid = fork();
  15. if (pid < 0) {
  16. printf("failed on fork (%s)\n", strerror(errno));
  17. return -1;
  18. }
  19. if (pid == 0) {
  20. struct timespec rem;
  21. rem.tv_sec = kill_parent ? 1 : 60;
  22. rem.tv_nsec = 0;
  23. printf("[pid=%d|ppid=%d] Going to sleep...\n", getpid(), getppid());
  24. nanosleep(&rem, 0);
  25. if (kill_parent)
  26. kill(parent_pid, SIGKILL);
  27. printf("[pid=%d|ppid=%d] Hello, Dad!\n", getpid(), getppid());
  28. return 0;
  29. }
  30. else {
  31. struct timespec rem;
  32. rem.tv_sec = kill_parent ? 60 : 1;
  33. rem.tv_nsec = 0;
  34. printf("[pid=%d|ppid=%d] Going to sleep...\n", getpid(), getppid());
  35. nanosleep(&rem, 0);
  36. if (!kill_parent)
  37. kill(pid, SIGKILL);
  38. printf("[pid=%d|ppid=%d] Hello, Kid!\n", getpid(), getppid());
  39. return 0;
  40. }
  41. }