我希望设计一个从中调用的函数main
,它将分叉任何进程进入睡眠状态,然后更新包含所有分叉 pid 和它们的计数器的“进程数组”。它似乎有效,只有其他进程也被分叉(这里是 pid-1
和11957
),我不确定从哪里来。测试运行给出:
Parent 11954 forks off children..
Children started: 2
Proc 11955 started
Proc 11956 started
Children started: 1
Child -1 terminated with status 0
Children started: 1
Proc 11957 started
Children started: 0
Child 11957 terminated with status 0
Child 11955 terminated with status 0
Child 11956 terminated with status 0
编码:
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#define MAXPROC 100
void fork_off(int * proc_t, int * proc_i) {
int f = fork();
if (f == 0) {
fprintf(stderr, "Proc %d started\n", getpid());
usleep(5000000);
} else {
proc_t[*proc_i] = f;
(*proc_i)++;
}
}
int main(void) {
int proc_table[MAXPROC], proc_index, status, i;
proc_index = status = i = 0;
printf("Parent %d forks off children..\n", getpid());
fork_off(proc_table, &proc_index);
fork_off(proc_table, &proc_index);
printf("Children started: %d\n", proc_index);
for (i = 0; i < proc_index; i++) {
printf("Child %d terminated with status %d\n",
waitpid(proc_table[i], &status, 0), status);
}
return 0;
}
我只想分叉两个进程,而不是更多。是什么导致了这种行为?