首先我们来看下fork函数的原型:
#i nclude <sys/types.h>
#i nclude <unistd.h>
pid_t fork(void);
返回值:
负数:如果出错,则fork()返回-1,此时没有创建新的进程。最初的进程仍然运行。
零:在子进程中,fork()返回0
正数:在父进程中,fork()返回正的子进程的PID
其次我们来看下如何利用fork创建子进程。
创建子进程的样板代码如下所示:
pid_t child;
if((child = fork())<0)
/*错误处理*/
else if(child == 0)
/*这是新进程*/
else
/*这是最初的父进程*/
fock函数调用一次却返回两次;向父进程返回子进程的ID,向子进程中返回0,
这是因为父进程可能存在很多个子进程,所以必须通过这个返回的子进程ID来跟踪子进程,
而子进程只有一个父进程,他的ID可以通过getppid取得。
下面我们来对比一下两个例子:
第一个:
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
int count=0;
pid = fork();
printf( "This is first time, pid = %d\n", pid );
printf( "This is second time, pid = %d\n", pid );
count++;
printf( "count = %d\n", count );</