0

I can not figure out what I have wrong with this code. This is C on a linux box.

What it should do is kill all the child processes I created, wait for the all to quit and then print out a line for each child with the pid, process number (I create), and the signal number (should be a 9 for killed).

So what am I doing wrong?

void onalarm(int signo) {
    int status[numberOfCores];
    printf("Recieved alarm signal\n");

    int cpu;
    for (cpu = 0; cpu < numberOfCores; cpu++) {
        kill(child_pid[cpu], SIGKILL);
    }

    for (cpu=0;cpu <numberOfCores;cpu++){
        waitpid(-1, &status[numberOfCores],0);
    }
    for (cpu=0;cpu < numberOfCores;cpu++){
        printf("pid = %i  %ith child killed with signal ",child_pid[cpu],cpu);

        printf("%i %s\n", WTERMSIG(status[cpu]), strsignal(WTERMSIG(status[cpu])));
    }
    exit(0);
Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • Shouldn't you do `waitpid` in the first for loop after kill? – Mohit Jain May 07 '14 at 02:44
  • What happens when you run it? – user3553031 May 07 '14 at 02:44
  • Now it does just what I expect. It sends the kill signal, then the waitpid waits for all of them to exit and it saves the exit status into the status array. With the waitpid outside of the kill array, it will send the kill to all child processess, then wait for them all to exit, if it is inside the first loop, it would end up doing the same thing. The only issue would be if a child exited before it got out of the kill loop into the waitpid loop. But this is a class exercise and it is how we were directed to do it. – user3088814 May 08 '14 at 04:54
  • Let me explain a little better. The main program creates a child process for each cpu core, that just runs a loop to waste time. The parent program sets an alarm for a time (command line option), then starts an infinite loop. When the alarm signal is received the parent runs this code, to send a kill to each child, and then prints out the exit status for each child. – user3088814 May 08 '14 at 04:56

1 Answers1

1

I figured out what my problem was.

     for (cpu=0;cpu <numberOfCores;cpu++){
    waitpid(-1, &status[numberOfCores],0);

Should be.

     for (cpu=0;cpu <numberOfCores;cpu++){
    waitpid(-1, &status[cpu],0);

Got it working correctly know. Thanks for helping me think.