snr*_*snr 2 c parallel-processing posix fork
我正在练习使用并行编程fork().我希望每个进程的父ID都是前进程的id,但在我的输出中显示相同的id.为什么?第二个问题是关于终止.有时输出显示所有进程,有时只有两个或三个,有时只有一个.为什么?我知道父母的过程应该等待它的孩子,但如果不是在我的问题中.我的困惑是,在fork()调用时,两个进程都是在不知道命令的情况下执行的,不是吗?也许父进程终止自己的执行.但它的孩子可以继续跑步到其余的节目或终止或其他什么?(因为它可以在输出上看到并不总是终止,也不总是完全正确)我不理解输出只显示一个但有时两个或三个或不是全部.我希望我能解释一下我的问题.看来,我做不到.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main (int argc, char *argv[]) {
pid_t childpid = 0;
int i;
for (i = 0; i < 3; i++)
if (childpid = fork())
break;
fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",
i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出(S):
i:0 process ID:2783 parent ID:1954 child ID:2784
i:1 process ID:2784 parent ID:1 child ID:2785
i:2 process ID:2785 parent ID:1 child ID:2786
i:3 process ID:2786 parent ID:1 child ID:0
or
//how??
i:0 process ID:3016 parent ID:1954 child ID:3017
i:1 process ID:3017 parent ID:1 child ID:3018
i:2 process ID:3018 parent ID:1 child ID:3019
or
//how??
i:0 process ID:4079 parent ID:1954 child ID:4080
i:1 process ID:4080 parent ID:1 child ID:4081
or
//how??
i:0 process ID:3038 parent ID:1954 child ID:3039
Run Code Online (Sandbox Code Playgroud)
预期产量:
i:0 process ID:2783 parent ID:1954 child ID:2784
i:1 process ID:2784 parent ID:2783 child ID:2785
i:2 process ID:2785 parent ID:2784 child ID:2786
i:3 process ID:2786 parent ID:2785 child ID:0
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
314 次 |
| 最近记录: |