子进程创建以及fork()函数的使用

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;
}
~                                                                                                      
~ 

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值