0

I am a beginner on C program, and got a question between worker process.
I write a program which fork a child process, inside the process, it create 2 threads to run and get some values from DB; however, if I fork 2 process, it will create 4 threads totally

I wonder the "extern variables" will be share within this 2 processes? Or independent?
If the variables are not shared, how could I maintenance the consistency between the processes?
(Sorry for my poor english)

Thanks all!!

moriya
  • 75
  • 9
  • As a sanity check, are you making sure that only the child process is executing the code that spawns 2 threads? – Dennis Meng Aug 30 '13 at 02:04
  • yes, I use ps -eLf to check how many threads it create from the child process – moriya Aug 30 '13 at 02:08
  • That's not what I asked. – Dennis Meng Aug 30 '13 at 02:09
  • Are you doing anything in the code to make sure that once you call `fork()`, only the child process (and not the parent process) is executing the code that spawns the threads? If you are not, then that would explain why 4 threads are getting spawned (2 from each) – Dennis Meng Aug 30 '13 at 02:12
  • you mean the parent process will spawns 2 threads also ? – moriya Aug 30 '13 at 02:18

1 Answers1

1

When you fork a process , both parent and child have their own separate address space and cannot communicate via variables. When you launch two threads (thread is a lightweight process) inside a process they share the address space of the process and can communicate via variables.

So the "extern variables " will be duplicated twice in your case and you cannot use them to communicate between the processes. To synchronize the two processes you need to use an IPC (inter process communicatin) mechanism such as (for example) a Shared memory for the storage coupled probably to a semaphore to prevent concurrent access.

Louis Hugues
  • 586
  • 4
  • 6