【问题标题】:In C Programming, how can you fork() a N number of function call to run in a child process?在 C 编程中,如何 fork() 在子进程中运行 N 个函数调用?
【发布时间】: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


【解决方案1】:

在 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()

【讨论】:

  • 那么我将如何执行函数1,然后函数2...函数N。我会做 ((childPid = fork()) == 0) {function 1} 然后 ((childPid = fork()) == 1) {function2}... ((childPid = fork()) == n) {函数N)?并感谢您的帮助
  • @bwan1011 不,fork() 返回进程 ID,不一定是有序的。这样做的唯一方法是:` if (i == 1) function1(); if (i == 2) 函数2(); ` 在 for 循环中。如果您只有 4 个函数,您可以计算模数 (i % 4 + 1),这将通过函数循环并“分配负载”
【解决方案2】:

我本身不是 c 程序员,但可以试试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-13
    • 2012-12-16
    • 1970-01-01
    • 2020-08-08
    • 2021-09-17
    • 1970-01-01
    相关资源
    最近更新 更多