首先,来看一下下面的源程序吧:
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid;
printf("Now only one process\n");
printf("Calling fork...\n");
pid = fork();
if(!pid)
{
// 这里是子进程执行的任务
printf("I'm the child, pid = %d, getpid = %d\n", pid, getpid());
}
else if(pid > 0)
{
// 这是父进程执行的任务
printf("I'm the parent, child has pid = %d, getpid = %d\n", pid, getpid());
}
else
printf("Fork failed\n");
return 0;
}
运行结果如下:
[root@test #59]#./p0
Now only one process
Calling fork...
I'm the child, pid = 0, getpid = 6164
I'm the parent, child has pid = 6164, getpid = 6163
可见:
在子进程中输出的pid是0,子进程的进程id是6164;
在父进程中输出的pid是6164(即子进程的进程id),父进程的进程id为6163。