/****fork_test.c *****/
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
main()
{
pid_t pid; /*此时仅有一个进程*/
int n=4;
pid=fork(); /*此时已经有两个进程在同时运行*/
if(pid<0)
printf("error in fork!\n");
else if(pid==0) /*返回0表示子进程*/
{
n++;
printf("I am the child process, my process ID is %d,n=%d\n",getpid(),n);
}
else /*返回大于0表示父进程*/
{
n--;
printf("I am the parent process, my process ID is %d,n=%d\n",getpid(),n);
}
}
语句“pid=fork()”,产生了两个进程,原来存在的父进程,新出现的子进程。
父子进程的区别除了PID不同fork函数的返回值也不相同。在父进程中,返回子进程Pid,子进程则返回0;