【发布时间】:2021-11-20 16:43:11
【问题描述】:
我想知道如何在 C 中 fork() N 个函数调用,其中一个函数在自己的子进程中获取它,而父进程将为每个子进程完成 Wait()。我在想所有的函数都可以同时运行,也就是函数 1 和函数 2 在同一时间运行。然后整个程序将完成(退出)。我的愿景是,您可以将 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;
}
我只是想涉足多线程/多进程编程,所以我完全希望 write/printf 语句在您产生多个进程线程时相互交错。而且我不是在处理不同功能中的共享内存。
意思:
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
如果我需要进一步澄清,请告诉我?
【问题讨论】:
-
你有什么问题?您可以将您的
fork()呼叫置于循环中。在子进程中,检查循环索引,并调用相应的函数,例如if (i == 0) { function1(); }
标签: c multithreading multiprocessing fork wait