c - 为什么在打印 "This is the child process!"后执行停止?

标签 c process fork

//Why not execute all the conditions(parent and child)?
#include<stdio.h>
#include<unistd.h>

int main(){
        pid_t pid; //process-id
        printf("This is where we start...\n");
        pid = fork();
//For the child process
        if(pid==0){
                printf("This is the child process!\n");
                return 1;
        }
//This should have been printed
        if(pid>0){
                printf("This is the parent!\n");
        }
//THis may/may not be printed - its ok
        if(pid < 0){ 
                printf("Fork failed!");
        }
        return 0;
}

异常(exception)的是,从 child 那里回来后, parent 应该被处决,但这是我得到的: $ 这是子进程!

我错过了什么?为什么不打印子 block 和父 block ?

最佳答案

程序完全没问题。执行 fork 时,会创建一个新的子进程。创建的子进程独立于父进程,父进程完全有可能不等待子进程完成执行。

如果您希望在子进程完成后继续执行父进程,您应该使用 wait() 函数,以确保在父进程继续之前执行 fork 的子进程。

尝试按如下方式更新您的代码:

#include<stdio.h>
#include<unistd.h>
#include <sys/wait.h>  //Add this header

int main()
{
        pid_t pid; //process-id
        int status;  //A variable to get the status of the child, i.e. if error or success
        printf("This is where we start...\n");
        pid = fork();
        if(pid==0){
                printf("This is the child process!\n");
                return 1;
        }
        if(pid>0){
                wait(&status);   //Function to wait for child
                printf("This is the parent!\n");
        }
        if(pid < 0){ 
                printf("Fork failed!");
        }
        return 0;
}

有关更多信息,请查看此链接:Forking a Process and Parent-Child execution - Linux : C Programming

关于c - 为什么在打印 "This is the child process!"后执行停止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37226137/

相关文章:

c - 提高并发进程的效率 - 设置 CPU 限制或其他?

c - 父进程调用fork()后子进程内存泄漏,为什么?

c - 使用管道将多个字符串发送到子进程

c - 添加一行代码改变变量的内存地址

c - 从C中的文件读取时无限循环

Java-获取父进程

java - 如何使用包含双引号的参数从 Java 启动进程

java - 指向结构指针的指针作为 JNA 中的参数

c - 知道 C 会让我用任何其他语言编写更好的代码的例子是什么?

C - 信号量未在所有进程上共享