现在我正在编写一个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.
}
}因此,例如,如果我尝试执行rm fileThatDoesntExist.txt,我会认为这是一个失败,因为文件不存在。我如何才能做到这一点呢?此外,虽然execvp()调用成功地执行了内置的shell程序,但它并不执行可执行文件的当前目录中的程序(即在其中运行此代码的程序);为了让它运行当前目录中的程序,我还需要做些什么吗?
谢谢!
发布于 2012-12-05 03:08:09
这是一个经典的问题,有一个非常优雅的解决方案。在派生之前,在父级中创建一个pipe。在fork之后,父级应该关闭管道的写入端,并阻止从读取端尝试read。孩子应该关闭读取端,并使用fcntl为写入端设置close-on-exec标志。
现在,如果子进程成功调用execvp,则管道的写入端将关闭,没有数据,父进程中的read将返回0。如果子进程中的execvp失败,则将错误代码写入管道,父进程中的read将返回非零值,并已读取错误代码以供父进程处理。
https://stackoverflow.com/questions/13710003
复制相似问题