跟踪进程的执行
Tracing the execution of a process
我有这段代码可以获取其进程 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() 生成多个进程,或 "child"。所以 parent 和 child 执行代码。 parent 的 pid > 0 而 child 的 pid ==0。
因此,parent 和 child 从 fork 命令开始在相似的时间执行。那么让我们从 parent 开始吧。 parent 检查第一条语句(pid > 0)并发现它为真,所以它打印出这两条语句。然后它一直到最后一个 else 之后的 print 语句。
现在进入 child。 child 检查第一个 if 语句,结果为假。检查下一个(pid == 0),发现是真的。所以现在它将打印出该声明。现在它将跳到 else 之后的打印语句并再次打印。
注意:parent 和 child 可以在不同的时间执行,因此如果您多次 运行 代码,输出的顺序可能会不同。
我有这段代码可以获取其进程 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() 生成多个进程,或 "child"。所以 parent 和 child 执行代码。 parent 的 pid > 0 而 child 的 pid ==0。
因此,parent 和 child 从 fork 命令开始在相似的时间执行。那么让我们从 parent 开始吧。 parent 检查第一条语句(pid > 0)并发现它为真,所以它打印出这两条语句。然后它一直到最后一个 else 之后的 print 语句。
现在进入 child。 child 检查第一个 if 语句,结果为假。检查下一个(pid == 0),发现是真的。所以现在它将打印出该声明。现在它将跳到 else 之后的打印语句并再次打印。
注意:parent 和 child 可以在不同的时间执行,因此如果您多次 运行 代码,输出的顺序可能会不同。