fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <signal.h>
  5.  
  6. int N = 5;
  7. int _pipe[2];
  8. pid_t children[5];
  9.  
  10. int main(){
  11. pid_t parent_pid;
  12. pid_t pid;
  13. int i = 0;
  14. int return_val; //we're not going to use this, but need it to call sigwait()
  15.  
  16. sigset_t set;
  17. sigfillset(&set);
  18. sigprocmask(SIG_BLOCK, &set, NULL);
  19.  
  20. parent_pid = getpid();
  21. fprintf(stderr,"I am main process, here comes my pid %u\n",getpid());
  22.  
  23. if (0>pipe(_pipe)) fprintf(stderr,"Error when creating pipe");
  24.  
  25. //Start creating child processes
  26. while (i < N){
  27. pid = fork();
  28. if (pid == 0){
  29. close(_pipe[1]);
  30. break;
  31. }
  32. else{
  33. fprintf(stderr,"Created child with pid %u\n",pid);
  34. children[i] = pid;
  35. write(_pipe[1],&pid,sizeof(pid_t));
  36. }
  37. i = i+1;
  38. }
  39.  
  40. i = 0;
  41.  
  42. // What main process does
  43. if (pid>0){
  44. close(_pipe[0]);
  45. close(_pipe[1]);
  46.  
  47. //sleep(2);
  48.  
  49. // Main process sends signal to each child
  50. while(i < N){
  51. kill(children[i],SIGUSR1);
  52. fprintf(stderr,"Sent SIGUSR1 to child %u\n",children[i]);
  53. // .. Now just wait for SIGUSR2 arrival
  54. sigwait(&set, &return_val);
  55.  
  56. i = i+1;
  57. }
  58. }
  59. // What children do
  60. else{
  61. // Wait for main process SIGUSR1 delivery
  62. sigwait(&set, &return_val);
  63.  
  64. fprintf(stderr, "SIGUSR1 arrived child %u from its father\n",getpid());
  65.  
  66. // Once SIGUSR1 has arrived, pipe is read N times
  67. while((i < N) && (read(_pipe[0],&pid,sizeof(pid_t))>0)){
  68. children[i] = pid;
  69. i = i+1;
  70. }
  71. close(_pipe[0]);
  72.  
  73. // After reading pipe, a reply is sent to parent process
  74. kill(parent_pid,SIGUSR2);
  75. }
  76.  
  77. return 0;
  78. }
Success #stdin #stdout 0.01s 1716KB
stdin
Standard input is empty
stdout
Standard output is empty