what happen if child and parent process read from the stdin at the same time?

Viewed 50

what happen if child and parent process read from the stdin at the same time?

int main(void){
int pid;
char    str[6];

str[5] = 0;
pid = fork();
if (pid)
{
    read(0, str, 5);
    printf("%s\n", str);
    waitpid(pid, 0, 0);
}
else
{
    read(0, str, 5);
    printf("%s\n", str);
}

as I expected, i will type the keyboard two times, hit enter twice, and it will show two results that I typed. But it didn't! so exactly what happened when two process request stdin at the same time??

1 Answers

For the sake of having a concrete example, I'll assume you typed foo⏎bar⏎. TTYs are line-buffered by default, so neither process will receive anything until you hit the Enter key the first time. Once you do, one of the processes (it's completely arbitrary whether it's the parent or the child, and may not even be the same across executions of the same binary on the same system) will get "foo\n" in its copy of str, and the return value of read will be 4. Once you hit the Enter key the second time, the other process will get "bar\n" in its copy of str, and its return value of read will also be 4. In this case, the two halves will be printed in the order you typed them in.

If you saw something different, it's probably because you typed more than 5 characters, including the Enter key. Again, for the sake of having a concrete example, assume you typed foobar⏎. Now, when you hit Enter, one of the processes will get "fooba" in str and have read return 5, and the other one will get "r\n" in str and have read return 2. In this case, the two halves could get printed in either order.

Also, by only setting the last element of str to 0, and then ignoring the return value of read, you risk printing garbage characters any time it reads less than 4 bytes.

Related