On Wed, Oct 16, 2013 at 5:15 PM, Friedrich Locke <friedrich.lo...@gmail.com>wrote:
> Hi folks, > > i am writing a program that: > > 0) manages to handle sigchld signals, > 1) creates 100 process > 2) put the childs to sleep 1 second > 3) loops (the parent process) until 100 child process have been died. > > It is not working, why ? > > Thanks for you time and cooperation. > > Best regards, > Fried. > > > PS: the source code below: > > #include <sys/types.h> > #include <sys/wait.h> > > #include <signal.h> > #include <stdio.h> > #include <unistd.h> > > unsigned long c; > > void > hdlchld(const int s) > { > unsigned long p; > int x; > > p = waitpid(-1, &x, WNOHANG | WCONTINUED | WUNTRACED); > fprintf(stdout, "%lu\n", p); > if (p + 1) { > c++; > fprintf(stdout, "pid: %lu\n died", p); > } > } > > int > main(int argc, char **argv) > { > struct sigaction s; > unsigned long i, p; > int x; > > s.sa_handler = hdlchld; > sigemptyset(&s.sa_mask); > sigaddset(&s.sa_mask, SIGCHLD); > s.sa_flags = 0; > > if (sigaction(SIGCHLD, &s, NULL) == -1) return 110; > > for (i = 0; i < 100; i++) { > p = fork(); > if (p == -1ul) break; > if (!p) break; /* child */ > } > if (p == -1ul) return 1; > if (p) while (c < i) sleep(1); /* parent */ > else sleep (1); /* child */ > return 0; > } > > - Declare p as pid_t in both functions. - Check fork's return value against -1 (not -1ul) - If you spawn n childs don't expect hdlchld to be called n times. I ran your program under linux (here, in my work, I don't have OpenBSD) and it run forever. Whth the following change the program works like, I suposse, you expect: void hdlchld(const int s) { pid_t p; int x; while(1){ p = waitpid(-1, &x, WNOHANG | WCONTINUED | WUNTRACED); fprintf(stdout, "%d\n", p); if (p > 0) { c++; fprintf(stdout, "pid: %d died (%lu)\n", p, c); } else break; } } Regards