gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:16:37 25 4
gpt4 key购买 nike

这是我的代码。我基本上想创建一个子进程,它将通过 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/

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