fork()函数,子进程与父进程之间的执行顺序不确定?

19 篇文章 0 订阅

fork()函数,子进程与父进程之间的执行顺序不确定?

回答:确实 ,子进程和父进程竞争CUP资源。

(相当于有两个进程同时运行,谁先运行要看他们谁先争取到的CUP资源(这里也有运行时间的,时间很短,当超过这个时间间隔,例如:10ms,就会停下进程(等待下回轮到它时会继续执行进程剩下的部分),去执行其他进程,当其他进程执行完成或者超过10ms))周期性

代码如下:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
        pid_t retpid;
        retpid=fork();

        pid_t pid = getpid();

        if(retpid > 0){
                printf("father  pid each run one\n");
                printf("retrun value:%d\n",retpid);
                printf("This is pid:%d\n",pid);
        }
        else if(retpid == 0){
                printf("child pid each run one\n");
                printf("retrun value:%d\n",retpid);
                printf("This is pid:%d\n",pid);
        }
        return 0;

}

运行结果:

CLC@Embed_Learn:~/LinuxLearn$ ./one
father  pid each run one
retrun value:20882
This is pid:20881
child pid each run one
retrun value:0
This is pid:20882
CLC@Embed_Learn:~/LinuxLearn$ ./one
father  pid each run one
child pid each run one
retrun value:0
This is pid:20884
retrun value:20884
This is pid:20883

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值