gpt4 book ai didi

c - 这个代码结果是什么?为什么会这样?

转载 作者:行者123 更新时间:2023-12-03 20:48:18 26 4
gpt4 key购买 nike

代码结果的原因是什么?
fork() 中发生异常时会发生什么? ?

#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main(){
int pid=fork();
if(pid==0){
int child=getpid();
printf("child: parent %d\n",getppid());
sleep(4);
printf("child: parent %d\n",getppid());
sleep(100);
}
else{
int parent=getpid();
printf("parent: parent %d\n",getppid());
sleep(2);
int zero=0;
int i=3/zero;
}
return 0;
}
这是输出:
parent: parent 63742
child: parent 63825
Floating point exception (core dumped)
ubunto@ubuntu:~/Desktop$ child: parent 4497

最佳答案

这是执行的时间顺序:
第二个 0:

  • fork()发出
  • 父进程打印其 pid (63742)
  • 子进程打印其 pid (63825)
  • 两个进程都发出 sleep

  • 第二个1:
  • 两个进程都在休眠

  • 第二个:
  • 父进程唤醒。子进程将再休眠 2 秒
  • 父进程发出除以 0 导致异常和程序异常终止

  • 为了深入检查父进程在其子进程之前终止时会发生什么,我建议检查 this questionthis other one .

    关于c - 这个代码结果是什么?为什么会这样?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64477991/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com