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?
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.
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.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With