kill.c 1.2 KB

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