子プロセスがファイルの実行に失敗したことをマスタープロセスがどのように知ることができますか?たとえば、次のコードでは、run()を使って0以外の値を返す方法を教えてください。ありがとう!execvとfork:子プロセスがファイルの実行に失敗したことを親に通知します
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
enum ErrorType { noError, immediateFailure, returnFailure, forkFailure };
using namespace std;
int run(void)
{
int error = noError;
//char proc[] = "/bin/uname";
char proc[] = "/usr/bin/Idontexist";
char *const params[] = {proc, NULL};
pid_t pid = fork();
printf("pid = %d\n",pid);
if (pid == 0)
{
if (execv(proc,params)==-1)
{
error = immediateFailure;
}
printf("child: error = %d\n",error);
}
else if (pid > 0)
{
/* This is the parent process
* incase you want to do something
* like wait for the child process to finish
*/
int waitError;
waitpid(pid, &waitError, 0);
if (waitError)
error = returnFailure;
printf("parent: error = %d, waitError = %d\n",error,waitError);
}
else
{
error = forkFailure;
}
return error;
}
int main(void)
{
printf("run() = %d\n",run());
return 0;
}
出力:execv
が失敗した後
pid = 4286
pid = 0
child: error = 1
run() = 1
parent: error = 0, waitError = 0
run() = 0