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