Yok*_*hen 2 c linux ubuntu process
所以我有以下C代码:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(){
int i = 0, n;
n = 5;
pid_t pid;
printf("i=%d Right before the loop\n", i, getpid(), getppid());
for (i = 0; i < n; i++){
pid = fork();
if (pid <= 0){
printf("something happens in loop #%d. pid = %d\n", i, pid);
break;
}
printf("End of loop #%d\n", i);
}
printf("i=%d My process ID = %d and my parent's ID = %d\n", i, getpid(), getppid());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我只有一个问题:为什么
printf("i=%d My process ID = %d and my parent's ID = %d\n", i, getpid(), getppid());
Run Code Online (Sandbox Code Playgroud)
多次被执行,好像它在循环中一样?我试图通过这么多方式弄清楚,但我找不到原因.
原因是fork()通过创建子进程来工作,该进程是在fork()调用时开始运行的父进程的副本.所以每个子进程都运行该printf命令.
例:
这是一个不太复杂的例子:
#include <stdio.h>
int main(){
int pid = fork();
if (pid == 0){
// child code
printf("child pid: 0\n");
}else{
// parent code
printf("parent pid: %d\n", pid);
}
// executed by both
printf("This text brought to you by process %d.\n", pid);
}
Run Code Online (Sandbox Code Playgroud)
如果要将某些代码限制为仅由子级或父级运行,则必须执行此类操作.
在我的机器上,当我刚运行它时,它会输出:
parent pid: 12513
This text brought to you by process 12513.
child pid: 0
This text brought to you by process 0.
Run Code Online (Sandbox Code Playgroud)
我的操作系统首先运行父进程,但它没有必要.
| 归档时间: |
|
| 查看次数: |
103 次 |
| 最近记录: |