I want to run some simple example to find out how fork()
system call work.
Its work but need to hit enter to exit the program after printing child process
.
#include <stdio.h>
#include <unistd.h>
int main()
{
pid_t pid;
pid = fork();
if(pid == 0){
printf("child process\n");
}
else{
printf("parent process\n");
}
return 0;
}
ss@ss:~$ gcc dd.c -o dd
ss@ss:~$ ./dd
parent process
ss@ss:~$ child process
after print child process on screen program need to hit enter key to return to the terminal.
Terminal wait for enter new command, if just hit enter return, write
ss@ss:
and OK.
Or we can enter any other terminal command and it executes.
I want to know why this behavior occur and if really program finished after printing child process
why terminal not show ss@ss:~$
Here is my machine information
gcc --version
gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
uname -a
Linux ss 4.8.0-36-generic #36~16.04.1-Ubuntu SMP Sun Feb 5 09:39:41 UTC 2017 i686 i686 i686 GNU/Linux
EDIT
Besides Felix Guo answer by adding wait(NULL)
after printf("Parent process")
, forced parent to wait for child process.
I find another way for it from by redirecting output of program to an arbitrary file with >
operator in terminal.
In execute command:
./dd > out.txt
it redirects outputs to out.txt file. if we cat this file:
$cat out.txt
parent process
child process
this is another way to see correct output of a program with fork()
.
[Edit 2]
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
pid = fork();
if(pid == 0){
printf("child process: \n\t");
printf("PID: %d\n\tPPID: %d\n", getpid(), getppid());
}
else{
printf("parent process: \n\t");
printf("PID: %d\n\tPPID: %d\n", getpid(), getppid());
wait(NULL);
}
return 0;
}
Output
parent process:
PID: 4344
PPID: 4336 < --- OS
child process:
PID: 4345
PPID: 4344 < --- parent process
Your parent process exits before waiting for your child process to complete, so the parent process will complete, which is what the terminal is waiting for, so the terminal will return to it's command input state, thus outputting ss@ss...
. Then your child processes prints and flushes stdout
to the screen, which then outputs child process
to the terminal, but since the terminal already outputted the prompt ss@ss
, it ends up after the prompt.
The way to solve this is to wait for the child process to exit before return 0
in the parent process. You can use wait(NULL)
after printf("Parent process")
to wait for child process as described here: Make parent wait for all child processes