Using shared memory with fork ()

I already looked at the only similar message I could find, but this is not what I was looking for.

Basically, I'm trying to start Odd-Even Sort using forking, so the child has odds and the parent works with alignment. They require the sharing of vector input values, as well as Boolean sorts.

The following code, without any unsuccessful attempts at memory exchange, is just the basic basis for using forks with a search algorithm:

while(!sorted) { pID = fork(); sorted = true; cout << "Sort set to TRUE." << endl; if(pID == 0) { int num = 1; cout << "Child swap run" << endl; Swap((void *) num); cout << "Status: " << ((sorted) ? "SORTED" : "UNSORTED") << endl; exit(0); } else if(pID < 0) { cout << "Failed to fork." << endl; exit(1); } else { wpid = waitpid(pID, &status, waitStatus); int num = 0; cout << "Parent swap run" << endl; Swap((void *) num); cout << "Status: " << ((sorted) ? "SORTED" : "UNSORTED") << endl; } } 

I tried several ways to hack this memory exchange, but I can not find a single resource that really explains how it works, what I need and the best way to do it.

So my requirements are as follows:

  • Parent and child must be able to share global vector and logical
  • It should be possible to execute in a loop as shown
  • This should work with variables that are used in main () and in the swap () function

If you have any advice, I will be very grateful to them. Thanks!

+7
source share
1 answer

You will need to use shmget() and shmat() to set the shared memory object, but unfortunately it will not be a dynamic memory object such as std::vector . In other words, you need to declare the entire size of the object at the initialization point of the shared memory object. The process, although quite straightforward, is that in your parent you call shmget() with the IPC_CREAT flag to create a shared memory object and get the identifier value for the object. Then call shmat() with the identification value to get a pointer to the object. Then initialize the object with the default values. When you redo your child process, the pointer returned from shmat() will still be valid in the child process, so you can exchange memory with both the parent and the child using the same pointer variable.

You will also want to declare in the parent process before migrating any semaphore using sem_init() with the pshared attribute set to a value greater than 0 . Then, both the parent and child processes can use the semaphore to control access to the shared memory object.

Again, keep in mind that the shared memory object is not a dynamic object, so you need to allocate enough space to initialize it.

+4
source

All Articles