c - fork()之后为什么子进程不执行?它永远不会涉及 child 的代码部分。

标签 c linux fork pid

这是我的代码。我基本上想创建一个子进程,它将通过 execvp() 执行一些命令。然而,该程序永远不会到达那里,因为它永远不会打印“Got to child”。我不明白为什么。有人可以解释错误是什么吗?因为我认为我正在按照 t 的程序进行操作。

    pid_t pid;
    pid = fork();

    if (pid < 0) { //if fork() returns less than 1 it failed
        fprintf(stderr, "fork failed");
        return 1;
    }
    else if (pid == 0) {  //for() returns 0 then this is the child process
        printf("Got to child");
        int exec;
        exec = execvp(args[0], args); /* (2) invoke execvp() */
        if (exec < 0) {
            printf("Error: executing command failed.\n");
            exit(1);
        }
    }
    else { //pid>0 therefore this is the parent process
        if (background == 0){
        wait(&status);
        printf("Got to parent");
        }
    }

最佳答案

这看起来像典型的模式,但我想知道是否

printf("Got to child");

没有\n 会导致未写入的缓冲区在 exec 发生时被丢弃,因此没有输出。

关于c - fork()之后为什么子进程不执行?它永远不会涉及 child 的代码部分。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21247314/

相关文章:

c - 如何使用 printf 在 C 中打印无穷大符号

c# - 将一个数字更改为另一个数字所需的位

c - LLVM 预编译连接问题

regex - 使用awk将第一列从十六进制转换为十进制

python - tee'd 生成器上的多处理

c - C 中的这种多管道代码有意义吗?

c - 使用函数和预设代码查找完美数字

linux - 查看已使用计算节点的CPU百分比

linux - 具有夏令时的 Ubuntu Amazon EC2 日期

c - 在 C.Fork() 中制作自定义 shell