Operating System - HP-UX
1833711 Members
2268 Online
110063 Solutions
New Discussion

Common Variable for Child Process

 
SOLVED
Go to solution
Alfonso_15
Advisor

Common Variable for Child Process

Hi Friends. I have a server in gcc. This server forks in 8 child process. How I can declare a variable coomon to all process: I means, if child process 1 changes its value, the other 7 process can see this new value.
Thanks,
alfonsoarias
3 REPLIES 3
A. Clay Stephenson
Acclaimed Contributor

Re: Common Variable for Child Process

Well, what you are talking about can be done if you use (actually misuse) vfork() rather than fork() but it depends upon the particular UNIX implementation. In any event, if that technique works, it works by accident and is NOT the way to do it.

The proper way to do this is to create a sharem memory shmment to which each process attaches. You should also make certain that a clean-up signal handler is in place to remove the shmid when all the processes using it terminate.

Man shmget,shmctl,shmat,ftok for details.
If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Common Variable for Child Process

I should also add that typically, in addition to shared memory, you also have to somehow ensure that only 1 process is changing a value at any one time. For this you need semaphores. Man semget, semop, and semctl for these issues.
If it ain't broke, I can fix that.
Ken_109
Advisor

Re: Common Variable for Child Process

Another technique is instead of creating 7 proccess, create 7 threads. Then the global memory is accessible from each thread. You will still need to protect this using a mutex. Much faster than semaphors and forking... see man pages, pthread_create, pthread_mutex_lock, pthread_mutex_unlock, pthread_cond_wait, pthread_cond_broadcast, pthread_cond_signall....etc...See Stevens or any primer on producer consumer problems. Also workq algorithm may be a good approach.