1、源代码
//The file name is forktest1.c
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<sys/types.h>
#include<unistd.h>int main()
{
pid_t n=fork(); //pid_t是进程号的定义类型,相当于int类型
assert(n!=-1);
if(n==0)
printf("hello\n");
else
printf("world\n");
// 显示父进程PID,与自己PID
printf("Parent PID= %d, My PID =%d \n",getppid(),getpid());
sleep(120); //进程后台运行时维持120秒
exit(0);
}
2、编译、后台运行
gcc forktest1.c -o forktest1 #gcc编译
./forktest1 & #运行加上&,表示后台运行
运行forktest1进程,进程号为6408,以此为父进程创建子进程(进程号为6409)。
记住这里的3010、6408、6409
3、进程示图
(1) ps -aefo user,ppid,pid,cmd
可以看到,bash(进程号3010),创建forktest1(进程号6408),forktest1进程通过fork()创建子进程forktest(进程号6409)
(2)pstree