Jake Evans
Jake Evans

Reputation: 1048

fork()ing - Idle Children

So I need to iterate fork() several times, creating child processes. The child processes are supposed to "do little or not processing" for example;

while(1)
 sleep(1)

The parent is then supposed to gather the PID's of the children and kill them (harsh, I know!).

However they way I'm doing it at the minute executes the code in the "parent" block several times, but I only need it to execute once.

Upvotes: 0

Views: 169

Answers (1)

Edouard Thiel
Edouard Thiel

Reputation: 6228

Here is an example; you need to store the pids in a table (here p[]).

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

#define NSUB 10

int main ()
{
    int i, n = NSUB, p[NSUB], q;

    for (i = 0; i < n; i++) {
        printf ("Creating subprocess %d ...\n", i);
        p[i] = fork();
        if (p[i] < 0) { perror ("fork"); exit (1); }

        if (p[i] == 0) {  /* subprocess */
            printf ("Subprocess %d : PID %d\n", i, (int) getpid());
            while (1) pause ();
            exit (0);
        }
    }

    sleep(2);
    for (i = 0; i < n; i++) {
        printf ("Killing subprocess %d ...\n", i);
        if (kill (p[i], SIGTERM) < 0) perror ("kill");
    }

    for (i = 0; i < n; i++) {
        printf ("waiting for a subprocess ...\n");
        q = wait (NULL);
        printf ("Subprocess terminated: PID %d\n", q);
    }

    exit (0);
}

Upvotes: 1

Related Questions