kill.c 1.1 KB

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