Kri*_* H. 5 c fork exec execvp
现在我正在编写一个必须执行子进程的C程序.我没有同时或任何事情做多个子进程,所以这是相当简单的.我肯定会成功执行内置shell程序(例如cat和echo之类的东西),但我还需要能够告诉其中一个程序何时无法成功执行.我正在尝试使用以下简化代码:
int returnStatus; // The return status of the child process.
pid_t pid = fork();
if (pid == -1) // error with forking.
{
// Not really important for this question.
}
else if (pid == 0) // We're in the child process.
{
execvp(programName, programNameAndCommandsArray); // vars declared above fork().
// If this code executes the execution has failed.
exit(127); // This exit code was taken from a exec tutorial -- why 127?
}
else // We're in the parent process.
{
wait(&returnStatus); // Wait for the child process to exit.
if (returnStatus == -1) // The child process execution failed.
{
// Log an error of execution.
}
}
Run Code Online (Sandbox Code Playgroud)
因此,例如,如果我尝试执行rm fileThatDoesntExist.txt,我想考虑一个失败,因为该文件不存在.我怎么能做到这一点?此外,虽然execvp()调用成功执行内置shell程序,但它不执行可执行文件的当前目录中的程序(即此代码在其中运行的程序); 为了让它在当前目录中运行程序,我还需要做些什么吗?
谢谢!
R..*_*R.. 16
这是一个非常优雅的解决方案的经典问题.在分叉之前,pipe在父级中创建一个.之后fork,父级应该关闭管道的写入端,并阻止read从读取端尝试.fcntl对于写入结束,孩子应该关闭读取结束并设置close-on-exec标志.
现在,如果子调用execvp成功,管道的写入结束将关闭而没有数据,并且read在父项中将返回0.如果execvp在子项中失败,则将错误代码写入管道,并且read在父项中将返回非零,已经读取了要处理的父代的错误代码.