原创作品转载请注明出处
编写程序创建进程树如图1和图2所示,在每个进程中显示当前进程识别码和父进程识别码。
1
#include<stdio.h>
int main()
{
int p1, p2, p3;//b, c, d
while((p1=fork()) == -1) ;
if(p1 != 0)
{
printf("process a\'s pid is %d, a\'s ppid is %d\n", getpid(), getppid());
}
else
{
while((p2=fork()) == -1) ;
if(p2 != 0)
{
printf("process b\'s pid is %d, b\'s ppid is %d\n", getpid(), getppid());
}
else
{
while((p3=fork()) == -1) ;
if(p3 != 0)
{
printf("process c\'s pid is %d, c\'s ppid is %d\n", getpid(), getppid());
}
else
{
printf("process d\'s pid is %d, d\'s ppid is %d\n", getpid(), getppid());
}
}
}
}
2
version 1
#include<stdio.h>
int main()
{
int p1, p2, p3, p4;//b,c,d,e
while((p1=fork()) == -1 || (p3=fork()) == -1) ;
if(p1 > 0 && p3 > 0)
{
printf("process a\'s pid is %d, a\'s ppid is %d\n", getpid(), getppid());
}
else if(p1 > 0)
{
while((p2=fork()) == -1) ;
if(p2 > 0)
{
printf("process b\'s pid is %d, b\'s ppid is %d\n", getpid(), getppid());
}
else
{
printf("process c\'s pid is %d, c\'s ppid is %d\n", getpid(), getppid());
}
}
else if (p3 > 0)
{
while((p4=fork()) == -1) ;
if(p4 > 0)
{
printf("process d\'s pid is %d, d\'s ppid is %d\n", getpid(), getppid());
}
else
{
printf("process e\'s pid is %d, e\'s ppid is %d\n", getpid(), getppid());
}
}
}
version 2
通过对fork返回的值是否为零,判断是否是在新建立的子进程中。
#include <stdio.h>
int main() {
int p_b, p_c, p_d, p_e;
while((p_b=fork()) == -1) ;
if(0 == p_b) {
while((p_c=fork()) == -1) ;
if(0 == p_c) {
printf("process c\'s pid is %d, c\'s ppid is %d\n", getpid(), getppid());
} else {
printf("process b\'s pid is %d, b\'s ppid is %d\n", getpid(), getppid());
}
} else {
while((p_d=fork()) == -1) ;
if (0 == p_d) {
while((p_e=fork()) == -1) ;
if (0 == p_e) {
printf("process e\'s pid is %d, e\'s ppid is %d\n", getpid(), getppid());
} else {
printf("process d\'s pid is %d, d\'s ppid is %d\n", getpid(), getppid());
}
} else {
printf("process a\'s pid is %d, a\'s ppid is %d\n", getpid(), getppid());
}
}
}
运行结果:
process a's pid is 3412, a's ppid is 2987
process b's pid is 3413, b's ppid is 3412
process c's pid is 3415, c's ppid is 3413
process d's pid is 3414, d's ppid is 3412
process e's pid is 3416, e's ppid is 3414
相关链接: