user629034
user629034

Reputation: 669

Variable scope in C

I have a main() function and prior to declaring main(), I declare global variables.

Then inside main() 2 processes start: 1 child and 1 parent via fork(). Why can't the parent and child processes share the global variables I declared? What is a good way to handle this? Thank you.

Upvotes: 0

Views: 493

Answers (2)

Patryk
Patryk

Reputation: 1441

With fork() you create a new process with separate memory space. To communicate between processes you can use signals (using kill())

If you want to share variables, consider using threads (e.g. pthread.h). Then you can use events or mutexes for thread synchronization.

Upvotes: 0

Brian Roach
Brian Roach

Reputation: 76918

When you fork() you're spawning a new process. Everything at the time of the fork is copied, but after that ... nothing is shared.

You have two choices at that point:

  • Keep a pipe open between your two processes and communicate changes
  • Re-write your code to be multi-threaded, where you can access the same data (using locks)

Upvotes: 4

Related Questions