kill.c 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. return 0;
  28. } else {
  29. struct timespec rem;
  30. rem.tv_sec = kill_parent ? 60 : 1;
  31. rem.tv_nsec = 0;
  32. printf("[pid=%d|ppid=%d] Going to sleep...\n", getpid(), getppid());
  33. nanosleep(&rem, 0);
  34. if (!kill_parent)
  35. kill(pid, SIGKILL);
  36. printf("[pid=%d|ppid=%d] Hello, Kid!\n", getpid(), getppid());
  37. return 0;
  38. }
  39. }