我找到了如何通过这样的方式来分叉多个孩子的例子:
if ( fork() = 0 ) {
//In child
} else {
if ( fork() = 0 ) {
//in second child
Run Code Online (Sandbox Code Playgroud)
但如果我不知道我需要多少个孩子,我该怎么办呢?
例如,如果我有一个链接的命令列表,我想为每个命令分叉和执行...所以我想我需要知道它是哪个孩子......
带上你的话,你需要为链表做这个:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这将为列表中的每个项目启动单独的过程.