这是我的代码.我基本上想要创建一个子进程,它将通过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");
}
}
Run Code Online (Sandbox Code Playgroud)
这看起来像典型的模式,但我想知道
printf("Got to child");
Run Code Online (Sandbox Code Playgroud)
没有\n会导致未写入的缓冲区在执行exec时被抛弃,因此没有输出.