#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main(){
pid_t pid;
pid = fork();
if(pid<0){
fprintf(stderr, "fork failed");
return 1; }
else if(pid == 0){
execlp("bin/ls", "ls", NULL);}
else{
wait(NULL);
printf("child complete\n");
}
return 0;
}
Here as far as I could understand, a child process is created and since its pid returned by fork is "0", it enters the block containing execlp and executes it, and then the parent waits till the child exits and then prints "child complete". Please correct me if I'm wrong. But I didnt understand how execlp() works here. Can someone explain this?
The arguments specified by a program with one of the exec functions are passed on to the new process image in the main() arguments. The path argument points to a path name that identifies the new process image file. The file argument is used to construct a pathname that identifies the new process image file.
execl() System Function: In execl() system function takes the path of the executable binary file (i.e. /bin/ls) as the first and second argument. Then, the arguments (i.e. -lh, /home) that you want to pass to the executable followed by NULL. Then execl() system function runs the command and prints the output.
The exec system call is used to execute a file which is residing in an active process. When exec is called the previous executable file is replaced and new file is executed. More precisely, we can say that using exec system call will replace the old file or program from the process with a new file or program.
execve() - Unix, Linux System Call.
fork
creates a new process, it is called once by the parent but returns twice in the parent and in the child.
In the child process the call execlp
executes the specified command ls
.
This replaces the child process with the new program file (ls
program file) which means following.
When a process calls the execlp
or one of the other 7 exec
functions, that process is completely replaced by the new program, and the new program starts executing at its main
function.
The process ID does not change across an exec
, because a new process is not
created.
exec
merely replaces the current process's text, data, heap, and stack
segments with a brand new program from disk.
The combination of fork
followed by exec
is called spawning a new process
on some operating systems.
Hopefully it was more or less clear. Let me know if you have more questions.
The exec() family of functions replaces the current process image with a new process image.
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