c - 当有多个 fork 进程在运行时,我无法理解流程

标签 c process fork exec

我正在运行一个运行多个进程(在本例中为命令)的程序。我坚持运行多个进程,因为它重复并多次运行代码片段。我在尝试了解正在发生的事情时遇到了很多麻烦。

我已经看过许多 youtube 视频和其他关于此的 SO 问题。

下面是我的代码的变体,包括伪代码:

int forking(char **command) {

pid_t parentPID = getpid();
pid_t childPID = fork();

if(childPID < 0) {
    printf("Fork failed\n");
} else if(childPID == 0) { //child process
    printf("Child PID: %d\n", getpid());
} else {
    printf("Parent PID: %d\n",
}

}

int main() {

    //open file of commands, each spaced by a newline

    printf("Main PID: %d\n", parentPID);
    while((getline(&command, &len_buffer, file_pointer)) != -1) {
        printf("-----------------\n);
        //parse command using strtok() to use execvp()
        pid = forking(parsed_command_array);
        if(pid == parentPID) {
            printf("This is the parent: %d\n", pid);
        else {
            printf("This is child, pid is: %d\n", pid);
        }
    }
}

它似乎为 2 个命令打印了以下输出:

------------------------
Main PID: 42729
Parent PID: 42729
This is parent: 42729
------------------------
Main PID: 42729
Child PID: 42730
This is child, pid is: 42730
------------------------
Main PID: 42729
Parent PID: 42729
This is parent: 42729
Child PID: 42731
This is child, pid is: 42731
Parent PID: 42730
This is child, pid is: 42730
Child PID: 42732
This is child, pid is: 42732

对于 while 循环中的每个命令,我希望代码能够: 1. 解析 execvp 的命令(我已经完成了) 2. 在函数中调用 fork 并返回 PID。如果PID是parent,忽略,如果PID是child,打印PID。

我还想把控制权留在父级,这样当我运行 fork 时,我想抓取子进程的 PID,在子进程中运行进程,然后回到父进程。

我只是不确定我做错了什么,我真的很困惑为什么父进程最初运行,然后在第二个循环中打印出子进程,然后在第三个循环中循环,它打印父级,然后打印命令 3 次。

最佳答案

在第一遍之后的 while 循环结束时,您有两个进程。这两个进程都回到循环的顶部,并且都派生出一个新进程。现在你有 4 个进程,在下一次迭代中它们都会 fork ,现在你有 8 个。

您希望子进程调用 exitexecvp 以便它不会继续循环。

关于c - 当有多个 fork 进程在运行时,我无法理解流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58383415/

相关文章:

c++ - 在特定点打印结构变量

c - 如何用 git 处理这个补丁问题?

在cmd提示符下编译C代码

python - 在运行时拦截子进程的标准输出

c - 使用跨叉继承的 stdio.h FILE * 流有哪些缺陷?

c - fork() 的功能

c - pmap 和 fork : where is my copy on write flag?

c++ - 无法解析 SystemC sc_signal_resolved

c - popen() 替代方案

c - 在进程通信中作为标准输入/标准输出的管道。