I have the following code in C:
if ((childpid = fork()) == 0) {
if (execvp(argv[0], argv) < 0) {
//execute failed
exit(1);
}
} else if (childpid < 0) {
//fork failed
} else {
//if execvp failed don't do anything here
//else do something
}
What I want is:
I enter a command.
If it is not executable it should not do anything but wait for my next entered command.
If it is executable it should do some things in the parent process.
If I enter e.g. sleep 1m
it should execute it in my child process, do things in the parent process and should be still able to execute more jobs (this works fine). But when I execute something like abcdef
(invalid command) it does the stuff in my parent process anyway.
Can someone tell me how the code should look like?
I also tried the following:
void signalHandler(int signal)
{
if (signal==SIGCHLD) {
printf("Child ended\n");
wait(NULL);
}
}
//in main
signal(SIGCHLD,signalHandler);
//...
if ((childpid = fork()) == 0) {
if (execvp(t_argv[0], t_argv) < 0) {
kill(getppid(),SIGCHLD);
}
}
Is this correct? This way I get an error afterwards (when it's finished).
waitpid(childpid, &status, WNOHANG)
tells me it finished with an error (-1).
One possible solution is to use a pair of anonymous pipes, where the child process writes in the write-end of the pipe any status it needs to pass on to the parent. Then in the parent you check the read-end of the pipe, if you don't receive anything before the child-process exits then everything was okay and the child process successfully executed the program.
If the parent does receive anything before the child process exits, then it means that the
exec
call failed.