home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.unix.programmer:5752 comp.unix.questions:14860
- Newsgroups: comp.unix.programmer,comp.unix.questions
- Path: sparky!uunet!psinntp!hyphenw!dwight
- From: dwight@hyphen.com (Dwight Ernest)
- Subject: Re: Programs that fork() don't redirect output in desired way?
- Message-ID: <1992Dec21.163718.5756@hyphen.com>
- Organization: Hyphen, Inc., Wilmington, MA 01887 USA / +1 508 988-0880
- References: <941@ncrsaud.SaudiArabia.NCR.COM>
- Date: Mon, 21 Dec 1992 16:37:18 GMT
- Lines: 48
-
- kbahey@ncrsaud.SaudiArabia.NCR.COM (Khalid Bahey-elDin) writes:
-
- >The following is the same on AT&T UNIX V.3 and V.4.
-
- >The scenario is that a program (a background communication interface) is
- >invoked, and it fork()s 2 children. The parent monitors both children, and
- >one child deals with inbound traffic, the other with outbound traffic.
-
- >In this program, we have a lot of printf()s used for debugging and tracing, and
- >are only active when we compile with a -DDEBUG compiler flag.
-
- >We let the program run in the background, and redirect stdout, and stderr to a
- >holding debug file, via the shell command:
-
- >prog > debug.out 2>&1
-
- >Because "prog" breaks itself into three running processes, we have three
- >different processes redirecting their output to the debug file.
-
- >The problem is that the file does not contain things in chronological order.
- >What happens is that it will contain output from the parent, then output from
- >child1, then output from child2, all interspersed.
-
- >I assume this is because of system buffering for printf()s.
-
- >Of course I can rewrite the printf()s so as they would write to a special log
- >file, but this would be a considerable effort, plus it will deprive us of the
- >flexibility of displaying output directly to the terminal when we want to.
-
- >What is an easy way to get the output of all three processes correctly in
- >correct chronological order?
-
- There's no clean way to completely avoid race conditions like you
- describe without a coding effort, which you say you're trying to
- avoid.
-
- A better algorithm, though, if you wanted to recode, would be to have
- the parent open the debug file instead of using redirection, and then
- use some sort of locking mechanism to allow one instance of the program
- to write to the output file at a time.
-
- A cheap and easy way to at least mitigate the effect would be to call
- fflush() after each printf. RTFM. It won't entirely do away with the
- problem, but it should help.
- --
- --Dwight A. Ernest R&D Manager (USA) I speak only for myself.
- Hyphen, Inc./181 Ballardvale St./Wilmington, MA 01887/+1 508 988 0880 x125
- dwight@hyphen.com
-