c - How can I make 'fork()'ed children share stdin? -


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("%d", &num);         printf("%d\n", num*num);     } } 

which supposed square 3 numbers reads stdin, not work expected. specifically, looks 1 of children "hogs" of catted input, since program this:

2 2 2 

to

4 0 0 

i think need use dup fix this, there nothing on in our course materials, , find on web way complicated me understand. how can make processes share stdin?

how can make 'fork()'ed children share stdin?

unless make provisions avoid it, children do share stdin. share the stream itself, conduit bytes. data transiting stream not part of stream.

specifically, looks 1 of children "hogs" of catted input,

yes. specific behavior not guaranteed, plausible , in fact likely. 1 process can read each byte -- removes byte stream, unavailable other processes. there fine details around interaction of buffering , forking might under circumstances produce appearance of different behavior, avoiding such complications important.

you need different communication pattern. here of more plausible alternatives:

  • pre-reading. original process reads needed data stream , records in memory. each fork()ed child inherits copy of data work with.

  • input multiplexing. main process or additional process sets takes responsibility reading stdin. forwards whatever reads each of other processes via pipes (one per each of 3 original children)

  • input bus. child processes connected via pipes (which can set on standard streams if desired); whatever data read forward next child on pipe, in addition performing regular work.


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 -