How can the master process know that the child process failed to execute the file (e.g. no such file or directory)? For example, in the following code, how can we get run() to return something other than 0? Thanks!
#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;
}
output:
pid = 4286
pid = 0
child: error = 1
run() = 1
parent: error = 0, waitError = 0
run() = 0