c - cat breaks the program, manual stdin input doesn't -


i have small program:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/wait.h>  int main() {     int orig = 1;     (int = 0; (i != 3) && orig; ++i) {         orig = orig && fork();     }     if (orig) {         (int = 0; != 3; ++i) {             wait(null);         }     } else {         int num;         scanf("%8d", &num);         printf("%d\n", num*num);     } } 

which supposed square 3 numbers reads stdin. , if type numbers in myself, works:

akiiino$ ./out.out 12345678 12345678 12345678 260846532 260846532 260846532 

but if use cat same purpose, not work expected:

akiiino$ cat in.txt 12345678 12345678 12345678  akiiino$ cat in.txt | ./out.out 260846532 0 0 

what reason behind weird behavior , fixable? i've assumed cating files no different typing them stdin.

the difference when type 3 numbers by hand, reading terminal , low level reads terminated on newlines. let's happens under hood.

  1. manual input:

    • the 3 child have started , waiting input
    • you type 1 number , new line
    • the underlying read call terminated newline because read terminal
    • first child (the 1 got read) has scanf call decode input processing

    ok, iterate same 2 other childs

  2. reading file or pipe

    • the 3 child have started , waiting input
    • the 3 numbers , newlines available
    • the underlying read of first child reads , consumes input in stdio buffer
    • first child (the 1 got read) has scanf call decode (first part of the) input processing

    but 2 other childs reading file/pipe positioned @ end of file. scanf returns 0 fail control it, , let initial undeterminated value in num.

you can control not problem of race condition adding sleep(10) before loop, starting program inputting hand 3 numbers before first child begins read. low level reads newline terminated (special tty case) still same output of first case, if 3 lines available before first read.


Comments

Popular posts from this blog

Command prompt result in label. Python 2.7 -

javascript - How do I use URL parameters to change link href on page? -

amazon web services - AWS Route53 Trying To Get Site To Resolve To www -