I try to learn who fork and execlp work but encountered with unexpected behavior. I think i missing something. as can see in my code in the child process the printf command not execute just the execlp and then the parent process, why it’s that? my expected print is: pid.c 5 10
but i got: pid.c 10
#include<stdio.h> #include<stdlib.h> #include<sys/wait.h> #include<unistd.h> int value = 10; int main() { pid_t pid; pid = fork(); if (pid == 0) { value -= 5; execlp("/bin/cat","cat","pid.c",NULL); printf("%dn",value); return 0; } else if (pid > 0) { wait(NULL); printf("%dn",value); return 0; } }
Advertisement
Answer
After a successful call to exec*()
the process image is replaced and the code after this call is not executed. So the
printf("%dn",value);
in the first conditional branch is never executed on success.
You would have to fork()
again solely for the execlp()
-call:
value -= 5; if (fork() == 0) { execlp("/bin/cat","cat","pid.c",NULL); exit(1); } wait(NULL); printf("%dn",value);
Btw. execlp()
is not meant to be used with an absolute path to the executable, that’s what execl()
is for.