Reputation: 5339
I trying a program with fork and execlp where parent address space is replaced with "ls" command.
#include<stdio.h>
main()
{
int pid,j=10,fd;
pid=fork();
if(pid==0)
{
printf("\nI am the child\n");
execlp("/bin/ls","ls",NULL);
printf("\nStill I am the child\n");
}
else if (pid > 0)
{
printf("\n I am the parent\n");
wait();
}
}
When I execute the program the last line of child
printf("\nStill I am the child\n");
is not printed. Why?
Upvotes: 7
Views: 34433
Reputation: 139
int
type but actually , to store process id you should use pid_t
printf
statement is not there in the new process , actually even the process id of the process is also not changedUpvotes: -3
Reputation: 21
The reason is simple : The exec() functions only return if an error has have occurred. For the same refer man pages of exec() functions.
What exactly is happening when exec() functions are called :
execl() does not create a new process - it modifies the VADS and associated contents - in addition, execution context is also modified.
Note: you must validate the return value of exec() family system call APIs for errors / error codes - based on the error/error codes, you may terminate the current process or take some other action.
Upvotes: 2
Reputation: 2101
after the function execlp() does not get executed as per the documentation of execlp hence your printf() statement "Still I'm the child" does not get executed ...!!
Upvotes: 0
Reputation: 5878
exec
functions will not merely execute your command. They will actually replace the execution context of the process by your selected executable (in your case /bin/ls
).
In other words, since the ls
function ends by terminating its process (thorugh 'exit' or returning the main function or whatever), your child process will be killed at the end of the execution of ls
.
You can actually use this printf call to print some errors, for instance:
if(pid==0)
{
printf("\nI am the child\n");
execlp("/bin/ls","ls",NULL);
printf("\nError: Could not execute function %s\n", "/bin/ls");
_exit(0); //make sure you kill your process, it won't disappear by itself.
}
Upvotes: 4
Reputation: 9733
exec
family functions do not return when successful.
http://pubs.opengroup.org/onlinepubs/009604499/functions/exec.html
The exec family of functions shall replace the current process image with a new process image. The new image shall be constructed from a regular, executable file called the new process image file. There shall be no return from a successful exec, because the calling process image is overlaid by the new process image.
If one of the exec functions returns to the calling process image, an error has occurred; the return value shall be -1, and errno shall be set to indicate the error.
Upvotes: 16