gpt4 book ai didi

c - 跟踪进程的执行

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:01 25 4
gpt4 key购买 nike

我有这段代码可以获取其进程 ID 及其父进程:

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main(){
int pid;
printf("I am the original process with PID %d and PPID %d. \n", getpid(), getppid());
pid = fork();

if (pid >0){
printf("I am the original process with PID %d and PPID %d \n", getpid(), getppid());
printf("My child’s pid is %d \n" , pid);
}
else if(pid == 0) {
printf ("I am the original process with PID %d and PPID %d \n", getpid(), getppid());
}
else if (pid == 1){
printf ("Error – no child process was created \n");
}else{
printf ("Error – system error \n");
}
printf (" PID %d terminates \n", getpid()); /* both processes execute this instruction */

return 0;
}

输出

I am the original process with PID 1009 and PPID 964. 
I am the original process with PID 1009 and PPID 964
My child’s pid is 1010
PID 1009 terminates
I am the original process with PID 1010 and PPID 1009
PID 1010 terminates

几个让我困惑的问题..这段代码是如何执行的?在输出中,您可以看到它运行 if(pid == 0) 下的代码,而条件 if(pid > 0) 已经执行。 pid怎么等于0?而它已经设置为大于 0。最后,fork() 到底做了什么?

最佳答案

fork() 生成多个进程,或一个“子进程”。所以 parent 和 child 执行代码。 parent 的 pid > 0, child 的 pid == 0。

因此,从 fork 命令开始,父进程和子进程在相似的时间执行。所以让我们从 parent 开始。 parent检查第一条语句(pid > 0),发现为真,于是打印出这两条语句。然后它一直到最后一个 else 之后的 print 语句。

现在给 child 。 child 检查第一个 if 语句,结果为假。检查下一个(pid == 0),发现是真的。所以现在它将打印出该声明。现在它将跳到 else 之后的打印语句并再次打印。

注意:父项和子项可以在不同的时间执行,因此如果您多次运行代码,输出的顺序可能会不同。

关于c - 跟踪进程的执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35251197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com