I already looked at the only similar post I could find, but it wasn't what I was looking for.
Basically, I'm trying to run the Odd-Even Sort with forking, so the child runs odds and parent runs the evens. These both require the sharing of the vector inputValues, as well as the boolean sorted.
The following code is without any of my failed attempts at sharing memory, and is just the basic framework for using forks with the 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've tried multiple ways of hacking out this sharing of memory, but can't find any one resource that really explains HOW it works, what I need, and the best way to do it.
So, my requirements are as follows:
- The parent and child must be able to share and manipulate a global vector and boolean
- This must be able to run in a loop, as shown
- This must work with the variables being used in main() and in the swap() function
If you have any tips, I'd greatly appreciate them. Thanks!
shm_openPOSIX API call. You want to create a shared-memory region, and put any variables accessed by both processes there. You could also do this with themmapcall pretty easily. Make sure to make your accesses thread-safe... There's no locking inherent in using shared memory, so you have to take care.shm_openyou'll need to then callftruncateto allocate space for the shared memory object, so again, the space in the memory object will not dynamically grow like you would see with astd::vector. You'll have to manually manage the size of the shared memory object at runtime if you need more space.