c - Using fork() in simplest form need to hit enter to finish execution -
i want run simple example find out how fork() system call work.
its work need hit enter exit 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; } compile, run & output
ss@ss:~$ gcc dd.c -o dd ss@ss:~$ ./dd parent process ss@ss:~$ child process after print child process on screen program need hit enter key return terminal.
terminal wait enter new command, if hit enter return, write ss@ss: , ok.
or can enter other terminal command , executes.
i want know why behavior occur , if program finished after printing child process why terminal not show ss@ss:~$
here 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 adding wait(null) after printf("parent process"), forced parent wait child process.
i find way from redirecting output of program arbitrary file > operator in terminal.
in execute command:
./dd > out.txt it redirects outputs out.txt file. if cat file:
$cat out.txt parent process child process this way see correct output of program fork().
your parent process exits before waiting child process complete, parent process complete, terminal waiting for, terminal return it's command input state, outputting ss@ss.... child processes prints , flushes stdout screen, outputs child process terminal, since terminal outputted prompt ss@ss, ends after prompt.
the way solve wait child process exit before return 0 in parent process. can use wait(null) after printf("parent process") wait child process described here: make parent wait child processes

Comments
Post a Comment