home *** CD-ROM | disk | FTP | other *** search
- Xref: sparky comp.lang.c++:11815 comp.unix.programmer:4025
- Newsgroups: comp.lang.c++,comp.unix.programmer
- Path: sparky!uunet!sun-barr!ames!elroy.jpl.nasa.gov!usc!rpi!batcomputer!munnari.oz.au!cs.mu.OZ.AU!munta.cs.mu.OZ.AU!fjh
- From: fjh@munta.cs.mu.OZ.AU (Fergus James HENDERSON)
- Subject: Re: How to avoid calling destructor twice after fork()?
- Message-ID: <9221212.11172@mulga.cs.mu.OZ.AU>
- Sender: news@cs.mu.OZ.AU
- Organization: Computer Science, University of Melbourne, Australia
- References: <1992Jul29.180655.4716@cis.ohio-state.edu>
- Date: Thu, 30 Jul 1992 02:44:35 GMT
- Lines: 57
-
- gyu@cis.ohio-state.edu (george yu) writes:
-
- >I am using fork() system call in my C++ program. The problem is that each
- >calling of fork() creates a copy of calling process. The problem is any
- >instances created and not destroyed before fork() calling will be
- >destroyed twice.
-
- [I'm cross-posting to comp.unix.programmer; you might get a more informative
- answer there]
-
- When you call fork(), it creates a copy of the data space of the program
- for the child. Thus parent and child each get their own copy of the stack,
- heap, and static data areas.
-
- This means that if the destructor is simply doing memory management, for
- example, then the destructor *should* be called twice, since it needs to
- call operator delete for both copies of the heap.
-
- If the destructor does some I/O (eg. closing a file), then the situation
- is more complicated. The simplest solution might be to bracket use of local
- variables using blocks, if this is possible:
-
- {
- local vars...
- some code...
- }
- pid=fork();
- {
- more local vars...S
- more code...
- }
-
- P.S.
- This is related to the following problem with C programs that use fork:
-
- #include <stdio.h>
- extern int fork(void);
-
- int main(void) {
- printf("Hello");
- fork();
- printf("\n");
- return 0;
- }
-
- You might expect this to print one "Hello" and two "\n"s.
- However because stdout is buffered, the "Hello" is not printed immediately.
- Thus the program forks, and then each copy contains "Hello" in the buffer
- for stdio. Now when each copy prints "\n", the buffer is flushed, so you
- get TWO "Hello"s as well as two "\n"s.
- (The solution here is to call fflush(stdout) before calling fork().)
-
- --
- Fergus Henderson fjh@munta.cs.mu.OZ.AU
- This .signature VIRUS is a self-referential statement that is true - but
- you will only be able to consistently believe it if you copy it to your own
- .signature file!
-