在C编程中,你怎么能fork() N个函数调用在子进程中运行?



我想知道如何在C中fork() N个函数调用,其中函数在自己的子进程中获得,父进程将等待()每个子进程完成。我认为所有的函数都是相互并发运行的,也就是function1和function2在同一时间运行。然后整个程序将完成(退出)。我的愿景是,您可以将Main()视为父进程(我知道fork复制项目文件中的所有代码),然后在Main()中,您可以在外部调用函数来运行特定算法,但在自己的进程中。以下是我在代码中的想法:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int function1() {
//Runs a specific algorithm in its own process
}
int function2() {
//Runs a specific algorithm in its own process
}
int function3() {
//Runs a specific algorithm in its own process
}
int function4() {
//Runs a specific algorithm in its own process
}
int main() {
//Main (thought as parent) calls function1... function4
//All functions are running at the same time or concurrently
//Each function gets their own child process

//each process runs and Main (or parent) waits for each function as a child process to complete 
//Then main(parent process) cleanly terminates
return 1;
}

我只是想让我的脚湿在多线程/多进程编程,所以我完全期望写/打印语句相互交错时,你产生多个进程线程。我不处理共享内存在'不同的功能。

的意义:

Prints from: function 1: Prints something 1
Prints from: function 4: Prints something 4
Prints from: function 2: Prints something 2
Prints from: function 3: Prints something 3
Prints from: function 1: Prints something 1
Prints from: function 1: Prints something 1
Prints from: function 2: Prints something 2  
如果我需要进一步澄清什么,请让我知道。

在main函数内部,您将启动一个for循环来创建所有子进程。

pid_t childPid, pid;
int status = 0;
for (i = 0; i < N; i++) {
if ((childPid = fork()) == 0) {
//execute function x for each one
exit(0);
}
}

然后等待所有子节点

while ((pid = wait(NULL)) > 0); //Wait for all child to complete

如果你想更精确,你可以存储pid,并使用相应的id调用waitpid()

我本身不是一个c程序员,但这里有一个尝试:

main内部,你叫fork(),如果返回值是0,你这个孩子,如果是零,你父,返回值是您刚才创建的孩子的PID。在子进程中,你可以调用你想要的函数,然后返回,在父进程中,你可以收集子进程的pid,并为每个子进程调用wait(),或者更好的是waitpid()

最新更新