开发者

Where to start when programming process synchronization algorithms like clone/fork, semaphores

开发者 https://www.devze.com 2022-12-24 22:49 出处:网络
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

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 ju开发者_如何学编程st 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消