views:

278

answers:

2

I am writing a program that simulates process synchronization. I am trying to implement the fork and semaphore techniques in C++, but am having trouble starting off. Do I just create a process and send it to fork from the very beginning? Is the program just going to be one infinite loop that goes back and forth between parent/child processes? And how do you create the idea of 'shared memory' in C++, explicit memory address or just some global variable? I just need to get the overall structure/idea of the flow of the program. Any references would be appreciated.

A: 

It is unclear from your question whether you really mean simulation or whether you are trying to access common process synchronization features from C++. Your reference to fork suggests that Linux is your target.

As soon as you create a new process, you're not simulating process synchronization, you are using the native synchronization capabilities of the operating system.

On Linux, to get shared memory, you would use mmap (perhaps with MAP_ANON) and then call fork. The resulting memory region will be shared. You can also use System V Shared Memory (the system calls whose names begin with 'shm'). Once you call fork, the child is a copy of the parent, but ordinary global variables don't end up shared: the child gets a new copy. Thus the need for mmap or shm.

On Windows, there is nothing like fork. You have to use named shared memory objects, or mapped files, to establish shared memory. The new process must make the necessary system calls to open the shared memory object or map the common file into its address space.

If you really do want to build a simulator -- a single process that internally manages processes and shared memory, you might want to pick up one of the various books that describe the internal working of Linux or Windows in this area.

bmargulies
A: 

So, this is the assignment. I assumed it was a kind of simulation, but perhaps my understanding is wrong. Since it's an assignment, I obviously don't want the exact code, but I just don't know how to start implementing this. As in, do I just start calling fork() from the main? And yes, I am using c++ on linux.

Make two processes, a reading process and a writing process that access a common buffer with a count variable as in the notes in class.

a. Process A writes to a buffer Z that is of length 100 at a rate of 1 sample per second.

b. Process B reads the buffer Z, but needs at least 50 samples of data to do its work. When it reads, it empties the whole buffer.

c. Processes can be created by: i. Fork() ii. Clone()

d. The common buffer will be created 1 or two ways: i. Using shared memory. ii. Using global memory and cloning processes.

e. Process communication can be accomplished using: i. The bakery algorithm: ii. Semaphores.

David