Linux Syscalls Fork
Linux Syscalls Fork
exec()
The exec() is such a system call that runs by replacing the current
process image with the new process image. However, the original
process remains as a new process but the new process replaces the
head data, stack data,etc. It runs the program from the entry point
by loading the program into the current process space.
To elaborate more, let's take an example as shown below.
$ sudo vim exec.c
main(void) {
pid_t pid = 0;
int status;
pid = fork();
if (pid == 0) {
printf("I am the child.");
execl("/bin/ls", "ls", "-l", "/home/ubuntu/", (char *) 0);
perror("In exec(): ");
}
if (pid > 0) {
printf("I am the parent, and the child is %d.\n", pid);
pid = wait(&status);
printf("End of process %d: ", pid);
if (WIFEXITED(status)) {
printf("The process ended with exit(%d).\n",
WEXITSTATUS(status));
}
if (WIFSIGNALED(status)) {
printf("The process ended with kill -%d.\n",
WTERMSIG(status));
}
}
if (pid < 0) {
perror("In fork():");
}
exit(0);
}
Output:
$ make exec
pid_t pid;
pid = fork();
if(pid==0)
{
printf("It is the child process and pid is %d\n",getpid());
int i=0;
for(i=0;i<8;i++)
{
printf("%d\n",i);
}
exit(0);
}
else if(pid > 0)
{
else
{
printf("Error in forking..\n");
exit(EXIT_FAILURE);
return 0;
}
Output:
$ make wait