Sunday 15 January 2012

multithreading - stdin, stdout and stderr are shared between? -



multithreading - stdin, stdout and stderr are shared between? -

i trying understand behavior of 3 streams - stdout, stdin , stderr. couldn't reply textbook, came here.

i know these 3 stored in file descriptor table file descriptors 0 (stdin), 1 (stdout) , 2 (stderr). aware these not simply file descriptors i/o streams can redirected. ok, how sharing?

consider 3 cases:

when fork() called : kid process , parent process shares file descriptors, have same stdin, stdout , stderr ? when thread created : threads share file descriptors, i/o streams? when execl() called : in case nowadays process image overwritten new process image. if execl("./a.out", "a.out", null); , new executable freshcopy of stdin, stderr , stdout?

all wise answers welcome.

in order understand what's going on, consider these communication channels across process boundaries. i'll avoid calling them streams, because used in different contexts, related.

now, firstly, filedescriptor index process-specific table represents these channels, kind of opaque handle. however, here first answer: since threads part of process, share these descriptors, if write 2 threads same channel, leaves through same channel, outside of process, 2 threads indistinguishable.

then, when fork() called, process copied. done copy-on-write optimizations, still, means have different tables representing these communication channels. entry index 2 in 1 process not same 1 index 2 in fork. same construction within process, if created c file* or c++ std::stream on top of one, gets copied, too, along other data.

when execl() called, process still "owns" channels outside. these assigned os manages processes. means index 2 can still used communicate outside world. on startup, runtime library create e.g. file* utilize in c 3 well-known channels stdin, stdout , stderr.

the question remains happens when process forked channels outside. here, reply simple, either channel closed or inherited, can configured on per-channel base. if inherited, remains usable in kid process. written inherited channel end wherever output parent process have ended up, too.

concerning stdin of forked process, i'm not sure, think input default 1 of closed, because sending input multiple targets doesn't create sense. also, never found need process input stdin in kid process, unless input provided parent process (similar pipes in shell, although siblings rather parent , child).

note: i'm not sure if description clear, please don't hesitate inquire , seek improve things understanding.

multithreading exec stdout stdin stderr

No comments:

Post a Comment