我已经找到了如何通过以下方式分叉多个孩子的示例:
if ( fork() = 0 ) {
//In child
} else {
if ( fork() = 0 ) {
//in second child
但如果我不知道我需要多少个孩子,我该怎么做呢?
例如,如果我有一个命令的链接列表,并且我想为每个命令分叉和执行......所以我想我也需要知道它是哪个孩子......
相信您需要为链表执行此操作:
linked_list_of_commands_t *node = root;
while (node != NULL) {
int pid = fork();
if (pid == -1) {
break; // handle error
} else if (pid == 0) {
// child
execv(node->command, node->argv);
exit(1); // execv should not return, but just in case the execv call fails
} else {
node = node->next;
}
}
这将为列表中的每个项目启动一个单独的进程。
但是例程的数量必须是固定的,即使在这些分支上的执行是无限的。那么对于每个例程都有某种 switch 语句逻辑的 while 循环呢?
怎么样
for (i=0; i< 1000; i++) {
pid = fork();
if (pid) {
// Error handling for pid==-1
break;
}
// Some logic dependent on value of 'i'
}
for(i = 0; i < num_children_to_spawn(); ++i) {
pid_t pid = fork();
if (pid == -1) {
exit(-1); /* error */
} else if (pid == 0) {
/* child */
do_child_things();
break;
} else {
/* parent */
}
}
请注意,我没有使用 switch() ,因为它会使break
退出循环变得更加麻烦。
pid_t children_pids[MAX_CHILDREN];
int last_child_index = 0;
for (int i=0; i < num_wanted_children; i++) {
pid_t pid = fork();
if (pid == 0)
// in child
else
children_pids[last_child_index++] = pid;
}