【问题标题】:Why the "return 0" statement did not reach? [closed]为什么“return 0”语句没有到达? [关闭]
【发布时间】:2021-02-12 01:19:27
【问题描述】:

这是我的程序:

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

int main(void) 
{ 
    
    int i;
    for (i=0; i < 3; i++) {
        int id = fork();
        if(id != 0) {
            printf("This process is running under parent process \n");
        }
        else {
            printf("This process id = %d, is a child process of parent process id = %d\n", getpid(),getppid());
        }
        return 0;
    }
}

当它完成第一个循环时,我假设它应该打印“这个进程正在父进程下运行\n”然后点击return 0; 语句。但它似乎没有达到我的预期。

这是我的输出

This process is running under parent process 
This process id = 839, is a child process of parent process id = 1

我需要解释一下。

【问题讨论】:

  • 那么你实际观察到的行为是什么?
  • “第一个循环” - 反正不会有任何其他循环。
  • 我认为你想要的是 return 0else 内(除非你希望子进程产生自己的子进程)然后在 for 之外让父进程等待所有子进程完成后再执行return 0

标签: c loops return fork


【解决方案1】:

在这种情况下,父进程在名为getppid() 的子进程之前退出,因此子进程被重新设置为 init。

由于您没有获得更多输出,显然已达到return 0;

fork() 被调用一次,但返回两次。这就是您获得新流程的方式。循环是不必要的。

此外,fork() 返回一个 pid_t 类型的变量,而不是 int。分配给类型int 似乎是安全的,但我被烧过一次。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-22
    • 2023-03-26
    • 2017-03-17
    • 2015-08-26
    • 2019-09-17
    • 2022-11-20
    • 2021-01-01
    • 1970-01-01
    相关资源
    最近更新 更多