负数:如果出错,则fork()返回-1,此时没有创建新的进程。最初的进程仍然运行。
零:在子进程中,fork()返回0
正数:在负进程中,fork()返回正的子进程的PID
#include <unistd.h>
#include <stdio.h>
int main()
{
pid_t pid;
int count=0;
pid = fork();
//父进程和子进程都从此处开始执行 ,所以可以看到打印结果中This is first time,This is second time 会被打印两次,
printf( "This is first time, pid = %d\n", pid );
printf( "This is second time, pid = %d\n", pid );
count++;
printf( "count = %d\n", count ); //那么count++ 应该执行两次,为什么两次打印都是1呢?那是因为fork之后,子进程和父进程的数据什么的,都分开了,
//各是各的,互不相干。
if ( pid>0 )
{
printf( "This is the parent process,the child has the pid:%d\n", pid );
}
else if ( !pid )
{
printf( "This is the child Process.\n")
//如果在此处处上 _exit(0); 那么 子进程将在此处结束, 不会继续往下执行
}
else
{
printf( "fork failed.\n" );
}
printf( "This is third time, pid = %d\n", pid );
printf( "This is fouth time, pid = %d\n", pid );
return 0;
}
打印结果:
父进程执行路径如下:
printf( "This is first time, pid = %d\n", pid );
printf( "This is secONd time, pid = %d\n", pid );
count++;
printf( "count = %d\n", count );
|
|
父进程 pid>0
if ( pid>0 )
|
|
printf( "This is third time, pid = %d\n", pid );
printf( "This is fouth time, pid = %d\n", pid );
return 0;
子进程执行路径如下:
printf( "This is first time, pid = %d\n", pid );
printf( "This is secONd time, pid = %d\n", pid );
count++;
printf( "count = %d\n", count );
|
|
子进程 pid==0
else if ( !pid )
{
printf( "This is the child Process.\n")
//如果在此处处上 _exit(0); 那么 子进程将在此处结束, 不会继续往下执行,也就是说,以下红色部分将不执行了,同理在父进程中也是如此
}
|
|
printf( "This is third time, pid = %d\n", pid );
printf( "This is fouth time, pid = %d\n", pid );
return 0;