Reputation: 2122
So I have a c program called "hello.c" that does nothing but "exit(2)" at the end. And I tried to run it in my child process, and then pass the return value into my parent process and print the appropriate messages. But somehow the program always exit at 0 and print the "exit at 0" message. Can someone tell me why?
pid_t pid;
int status;
pid = fork();
if (pid == -1){
perror("fork");
exit(1);
}
if (pid >0){
/*abusive parents*/
waitpid(pid, &status, 0);
if(WEXITSTATUS(status)==3){
printf("exit at 3\n");
}
if(WEXITSTATUS(status)==2){
printf("exit at 2\n");
}
if(!(WEXITSTATUS(status))){
printf("exit at 0\n");
}
}
else{
/*stupid child*/
execlp("hello.c",NULL);
}
return 0;}
Here is the hello.c:
int main(void){
int teemo=0;
exit(2);
}
Upvotes: 0
Views: 15117
Reputation: 1
Just to add why its returning zero always in this case
This is because when execlp was failing and returning -1, parent process was using return value at the end of the main function i.e. 0 in this case. If you change this to 2 or 3 you will see program hitting that code with if check ==3 or ==2.
Upvotes: 0
Reputation: 70981
(Not only) to better understand what is happeing in your code, add error checking.
In your specific case add it at least to the call to execlp()
. To do so first have a look at exec*()
s documentation:
RETURN VALUE
The exec() functions only return if an error has have occurred. The return value is -1, and errno is set to indicate the error.
And then enhance your code to cover this case:
...
}
else /* child */
{
if (-1 == execlp("hello.c"))
{
perror("execlp() failed");
return 1;
}
}
return 0;
}
You will observer an error message regarding the call to execlp()
.
This dues to hello.c
most probably not being an executable, but an ordinary text file, C-source.
Looking at the documentation closer one reads:
The list of arguments must be terminated by a null pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.
From this we learn that a call to the execl*()
members of the exec*()
family of functions shall always end like this:
execlp(..., (char *) NULL)
Upvotes: 1
Reputation: 15121
You cannot run a C source file, you need to compile (and link) it to generate an executable file, and run this file. Therefore, you should do something like
Compiling hello.c
first (I suppose you are using gcc
)
gcc -o hello hello.c
Runing hello
in your first program like this
execlp("./hello", "hello", NULL);
Then you should get what you expected.
Upvotes: 2