fork()ing - 空闲的孩子

时间:2013-02-28 16:20:13

标签: c process fork

所以我需要多次迭代fork(),创建子进程。例如,子进程应该“做很少或不做处理”;

while(1)
 sleep(1)

然后父母应该收集孩子的PID并杀死他们(严厉,我知道!)。

然而,我这样做的方式在一分钟内执行“父”块中的代码几次,但我只需要执行一次。

1 个答案:

答案 0 :(得分:1)

这是一个例子;你需要将pid存储在一个表中(这里是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);
}