In bash, when I type ls
and hit enter, the binary ls
will run and I will return to shell prompt again without doing anything from my side.
However this program, written in C will block:
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
int main(void)
{
pid_t other = fork();
// other will be 0 for the child process
// other will be the childs process' value in the parent process.
switch(other) {
case 0:
printf("%s %i\n", "I am the child process!", other);
execl("/bin/ls","ls",NULL);
return 0;
default:
printf("%s %i\n", "I am the parent process!", other);
return 1;
}
}
Why?
The output is as follows:
Korays-MacBook-Pro:~ koraytugay$ ./a.out
I am the parent process! 40309
I am the child process! 0
Korays-MacBook-Pro:~ koraytugay$ AndroidStudioProjects Movies happyko koray.i
Applications Music hello.c koray.o
ClionProjects Pictures hello.sh koray.s
Code Public innbound mssql
Desktop TheElementsFiles innbound-pf nono.txt
Documents VirtualBox VMs innbound_usage.log svn-key
Downloads a.out k.txt tugay.c
IdeaProjects asm.asm klinnck webtoolkit
Koray.class asm.hack klinnck-pf
Koray.java cexamples koray.a
Library fifa.sql koray.c
At this point I will need to hit Enter so that I return to bash prompt. Why?
At this point I will need to hit ENTER so that I return to bash prompt.
Actually, you're already back to the prompt, you just did not realize it.
To elaborate, the problem you facing here is, the parent does not wait for the child to exit and returns beforehand the child finishes execution. So, the shell prompt comes back, and then the output from the chlid process (output of ls
) gets printed on the output.
If you notice properly, You've already got the prompt back, and your output appears later.
Korays-MacBook-Pro:~ koraytugay$ ./a.out
I am the parent process! 40309
I am the child process! 0
****Korays-MacBook-Pro:~ koraytugay$***** AndroidStudioProjects Movies happyko koray.i
Applications Music hello.c koray.o
ClionProjects Pictures hello.sh koray.s
Code Public innbound mssql
Desktop TheElementsFiles innbound-p
Above, please note the ****
marked line. There, you got your shell prompt back.
At this point I will need to hit Enter so that I return to bash.
Except no, you're already in bash. But all that ls output after the prompt makes it seem that you are not. Go ahead, try another command.
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