This is the mail archive of the
gcc@gcc.gnu.org
mailing list for the GCC project.
problem about constructor and destructor with fork()
- To: gcc at gcc dot gnu dot org
- Subject: problem about constructor and destructor with fork()
- From: Jerry Hong <jhong001 at yahoo dot com>
- Date: Mon, 2 Apr 2001 14:00:35 -0700 (PDT)
Hi,
Sceniaro: (Code attached) Global C++ object which
keep a piece of shared memory. The purpose of the
shared memory is to keep how many process of mine
currently in the system. As the process creates, the
object Constructor is called and process number
increased by 1, and as the process exits, the
Destructor is called, the process number decreased by
1.
If I create 2 process in a different shell, that
works fine.
However, if fork() another process, I have a
problem. When the 1st process create, it constructs
the oject by calling its Constructor, *proc_num =1,
then it fork(), creating the 2nd process. But the 2nd
process inherits all the evironment from the 1st
process, the Constructor never gets called. Then both
processes exit by calling the destructor, the final
result is *proc_num = -1.
Any idear for solution based on this Global C++
object. By the way, here I just simplified the case
from our real project to illustrate the point, and I
don't want to get rid of this Golbal C++ object.
Any comments welcome.
test.c
class Pclass
{
....
int* proc_num;
//* proc_num points to a shared memory.
//keep how many process of mine in the system.
..
} my_object;
Pclass::Pclass()
{
..
*proc_num = *proc_num + 1;
..
}
Pclass::~Pclass()
{
..
*proc_num = *proc_num - 1;
..
}
main()
{
fork(); //create another process.
}
__________________________________________________
Do You Yahoo!?
Get email at your own domain with Yahoo! Mail.
http://personal.mail.yahoo.com/?.refer=text