I have a piece of code to print out PID's once Forked, and just a basic user input thing, but each time I run the script, sometimes it runs as expected and it all prints out within one command, then the next time the child prints it's PID, it does so on a next line and leaves the terminal in a state in which you need to press enter for it to continue. I've researched this website about people flushing at what not, which I've added literally everywhere but I still can't get it to work.
My code:
#include <unistd.h>
#include <stdio.h>
#include "sys/types.h"
int main(){
int pid;
int userInput;
printf("Please enter a number: ");
userInput = getchar();
printf("\nYou entered: ");
putchar(userInput);
printf ("\n");
fflush(0);
pid = fork();
if (0 == pid)
{
printf ("I am the child process, my PID is %d \n", getpid());
fflush(0);
}
else
{
printf ("I am the parent process, my PID is %d \n", getpid());
fflush(0);
}
return 0;
}
And this is what happens when I run it a few times:
Could someone point out where I've gone wrong and how to correct it?
Thanks!
Forking a process prints differently each time ? when you do fork()
1st parent
will run and it runs in foreground
and then child
will run and its run in background
. Now reason you are getting differently because if foreground process completed background process comes to foreground & displayss its output & vice versa.
If command prompt is free i.e if parent completed then child will come to foreground & displays its output, shell won't stop child process being executed on foreground.
Note that sequence of execution of child & parent process may defer as its OS dependent.