fork download
  1. #include <signal.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <inttypes.h>
  5. #include <unistd.h>
  6. #include <sys/types.h>
  7.  
  8. #define MAGIC 42
  9. #define P 2048
  10.  
  11. int *f(void) {
  12. static unsigned offset = 0;
  13. volatile int data[P];
  14. offset = (offset + 1) % P;
  15. data[offset] = MAGIC;
  16. return &data[offset];
  17. }
  18.  
  19. int check() {
  20. int value;
  21. int *m = f();
  22. value = *m;
  23. return value == MAGIC;
  24. }
  25.  
  26. void loop() {
  27. do {} while (check());
  28. puts("Oops.");
  29. }
  30.  
  31. static void catch_function(int signal) {
  32. int foo[100], i;
  33. if (signal == SIGCHLD) {
  34. printf("Caught the SIGCHLD signal. Exiting.\n");
  35. exit(EXIT_SUCCESS);
  36. }
  37. for (i = 0; i < 100; i++)
  38. foo[i] = i * i;
  39. }
  40.  
  41.  
  42. int main(void) {
  43. if (signal(SIGUSR1, catch_function) == SIG_ERR || signal(SIGCHLD, catch_function) == SIG_ERR) {
  44. fputs("An error occurred while setting a signal handler.\n", stderr);
  45. return EXIT_FAILURE;
  46. }
  47.  
  48. pid_t chpid = fork();
  49. if (chpid == -1) {
  50. fputs("An error occurred while forking child process.\n", stderr);
  51. return EXIT_FAILURE;
  52. }
  53.  
  54. if (chpid == 0) {
  55. pid_t parent = getppid();
  56. do {} while(kill(parent, SIGUSR1) == 0);
  57. perror("Kill");
  58. } else {
  59. loop();
  60. }
  61. puts("Exiting.");
  62. return 0;
  63. }
  64.  
Success #stdin #stdout 2.63s 1720KB
stdin
Standard input is empty
stdout
Oops.
Exiting.