[LC++]IOStreams and forking.

Jack Lloyd lloyd at acm.jhu.edu
Wed Nov 6 01:54:01 UTC 2002


I doubt any standard has been defined; ISO C++ doesn't mention threads, and
the thread/IPC standards (POSIX, Unix98, etc) don't mention C++. Basically
"it depends". And as you have found, relying on it is a bad idea. :(

There are a few other options that come to mind, which may or may not be
useful:
  Use threads instead of fork()
  Use syslog()
  Write a log daemon (or reuse one somebody else has written) and talk to
    it over a Unix domain socket (preferably wrapped inside a function ala
    syslog)
  Keep the logging file open as a Unix file descriptor.

BTW, be careful about multiple processes writing to the file at once: they
could easily overlap in their outputs, etc. Consider fcntl() locking, or a
central log server, to solve that problem. HTH.

Regards,
  Jack

On Tue, 5 Nov 2002, David wrote:

> Hi,
>
> I have a program that opens a file (used as a log) then forks to create N
> number of children.
>
> My question is, in C++ when I call fork(), is the file supposed to stay
> open or not?
>
> I know that in C all open file descriptors are copied to the new process,
> but does the same apply to iostreams?
>
> At the moment, I seems to lose any IO to the file after the 1st fork.




More information about the tuxCPProgramming mailing list