I am using fork and the child process reads data ten times from user using a scanf inside the for loop. The parent process however sends the SIGSTOP signal to child after 4 seconds of sleep and reads a value from the user and prints it. But if the user has entered data but not pressed enter for the scanf in the child process the parent process reads but prints the data written in the child process. How do I stop this from happeneing.
ch=fork();
if(ch==0)
{
for(i=0;i<10;i++)
{
fflush(stdin);
scanf("%s",buf);
printf("%d: %s\n",i,buf);
}
}
else
{
char buf2[100],cha;
sleep(4);
kill(ch,SIGSTOP);
write(STDOUT_FILENO,"\nchld stopped\n",14);
memset(stdin,0,sizeof(stdin));
read(STDIN_FILENO,buf2,2);
write(STDOUT_FILENO,buf2,2);
kill(ch,SIGCONT);
wait(SIGCHLD);
}
So the output for example comes like this:
a
0: a
b
1: b
ac (I dont press enter here and wait for SIGSTOP)
chld stopped
tr (Entered data for parent and pressed enter)
ac2: tr
c
3: c ... and so on
So after entering tr why does my parent display ac?
Okay I found the solution.
I used tcflush(): flush non-transmitted output data, non-read input data, or both.
tcflush(STDIN_FILENO,TCIFLUSH); line just before the read in the parent did it.
I found the solution here... How can I flush unread data from a tty input queue on a UNIX system?