fork函数简单示例

一句话总结主题:如果fork调用成功的话,在父进程中返回子进程的PID,在子进程中返回0

如何理解这句话呢?

/* file main.c*/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main ()
{
          pid_t ret_pid;
          ret_pid=fork();
          if (ret_pid < 0)
                  printf("error in fork!");
          else if (ret_pid == 0)
                  printf("i am the child process, my process id is %d, ret_pid=%d. \n", getpid(), ret_pid);
          else
                  printf("i am the parent process, my process id is %d, ret_pid=%d. \n", getpid(), ret_pid);
          return 0;
}


编译执行(注意 *.c,用gcc;对于*.cpp,要使用g++):

>> gcc main.c
>> ./a.out

结果是:

i am the parent process, my process id is 25711, ret_pid=25712.
i am the child process, my process id is 25712, ret_pid=0.
  • ret_pid的值小于零,说明fork函数执行出错;
  • ret_pid的值是零,说明此时是在子进程中,通过getpid()得到子进程PID号,即25712;
  • ret_pid的值大于零,说明此时是在父进程中,通过getpid()得到父进程的ID,即25711, 并且此时ret_pid的值是25712,即子进程的PID号;

参考:关于fork函数的作用

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值