所以我有以下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;
}
我只有一个问题:
为什么
printf("i=%d My process ID = %d and my parent's ID = %d\n", i, getpid(), getppid());
被执行很多次,好像它在循环内一样?我试图通过很多方法来弄清楚,但我找不到原因。
最佳答案
原因是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);
}
如果要限制某些代码仅由 child 或 parent 运行,则必须执行类似的操作。
在我的机器上,当我刚运行它时,它输出:
parent pid: 12513
This text brought to you by process 12513.
child pid: 0
This text brought to you by process 0.
我的操作系统先运行父进程,但不必这样做。
关于c - 不应该循环的代码(使用fork)正在循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18907629/