2. Linux创建进程 fork的使用

fork函数初用

了解了进程的相关概念后,我们来最简单的试用以下进程。
查看手册,fork函数
在这里插入图片描述可以看到,调用fork后,会立刻创建一个子进程,我们简单看看效果,打印一下自己的进程号。

 

int main(){

   pid_t pyd;
   pid_t qinyu;
   pyd=getpid();
      printf("befor getpid is : %d\n",pyd);
   fork();
   qinyu=getpid();
      printf("aftere getpid is : %d\n",qinyu);

    if(pyd==qinyu){
        printf("the is  father getpid\n");
    }
     else{
        printf("the is person getpid,have  is : %d\n",qinyu);
     }

getpid() //获取自身进程   

调用fork()后形成又一个进程,程序又从fork开始又走一遍

befor getpid is : 18337
aftere getpid is : 18337
the is  father getpid
CLC@Embed_Learn:~/proceed$ aftere getpid is : 18338
the is person getpid,have  is : 18338

使用fork函数创建一个进程

pid_t fork(void);  

fork函数调用成功,返回两次

返回值为0,     代表当前进程是子进程

返回值非负数,代表当前进程为父进程


   pid_t pyd;
      printf("father getpid is : %d\n",getpid());

   fork();
      if(pyd>0){
        printf("the is  father getpid\n",getpid());
    }
     else if(pyd==0){
        printf("the is person getpid,have  is : %d\n",getpid());
     }

 return 0;
father getpid is : 18419
the is person getpid,have  is : 18419
CLC@Embed_Learn:~/proceed$ the is person getpid,have  is : 18420

调用失败,返回-1

父进程和字进程一目了然了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追着太阳跑1

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值