fork调用的一个奇妙之处就是它仅仅被调用一次,却能够返回两次,它可能有三种不同的返回值:
1)在父进程中,fork返回新创建子进程的进程ID;
2)在子进程中,fork返回0;
3)如果出现错误,fork返回一个负值;
在fork函数执行完毕后,如果创建新进程成功,则出现两个进程,一个是子进程,一个是父进程。在子进程中,fork函数返回0,在父进程中,fork返回新创建子进程的进程ID。我们可以通过fork返回的值来判断当前进程是子进程还是父进程。
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<sys/stat.h>
int main()
{
pid_t pid;
int count=0;
printf("the result111 of the count : %d \n",count);
pid = fork();
printf("main the fork is %d\n",pid);
if(pid>0)
{
printf("the child pid is : %d\n",pid);
printf("the father pid is : %d \n",getpid());
count++;
}
else if(pid==0)
printf("my pid is :%d \n",getpid());
else printf("fork failed \n");
count++;
printf("the result of the count is : %d\n ",count);
return 0;
}
输出的结果为:
the result111 of the count : 0
main the fork is 15218
the child pid is : 15218
the father pid is : 15217
the result of the count is : 2
main the fork is 0
my pid is :15218
the result of the count is : 1
由此可见:子进程在创建的时候会复制父进程的资源,子进程使用的复制资源(如变量的值)对父进程没有影响,两个进程是完全独立的。且子进程在fork()之后开始执行命令,对于fork()之前的命令不加以执行。
睡眠与阻塞
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main()
{
pid_t pc,pc1,pc2;
pc=fork();
if(pc<0) printf("error fork\n");
else if(pc == 0)
{
printf("0000000000000=pid=%d\n",getpid());
sleep(6);
printf("0000000000000=pid=%d\n",getpid());
// exit(0);
}
// if(pc>0) printf("1111111111111=pid=%d\n",getpid();
pc1=fork();
if(pc1==0){
printf("1111111111111=pid=%d\n",getpid());
sleep(8);
printf("1111111111111=pid=%d\n",getpid());
exit(0);
}
if(pc>0){
printf("6666666666666=pid=%d\n",getpid());
}
printf("========pid=%d\n",getpid());
wait(NULL);
exit(0);
return 0;
}
~
~