Reputation: 1
I am trying to lock my shared memory array so that only one process can modify it at a time. One process appends 5 same values to my shared memory and then it unlocks it for the other waiting process. I tried to print the whole array before unlocking the mutex for every process and it seems that other processes can modify my shared array. Here is my code which does the above:
#include<bits/stdc++.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <pthread.h>
#include <mutex>
using namespace std;
mutex mut;
int main(){
int shmid5 = shmget(IPC_PRIVATE, 30*sizeof(int), 0777 | IPC_CREAT);
int *number = (int *)shmat(shmid5, 0, 0);
int shmid6 = shmget(IPC_PRIVATE, sizeof(int), 0777 | IPC_CREAT);
int *counter = (int *)shmat(shmid6, 0, 0);
int shmid7 = shmget(IPC_PRIVATE, sizeof(int), 0777 | IPC_CREAT);
int *value = (int *)shmat(shmid7, 0, 0);
*counter=0;
*value=0;
for(int i=0;i<2;i++){
fork();
mut.lock();
(*value)++;
for(int j=0;j<5;j++){
number[*counter]= *value;
(*counter)++;
sleep(2);
}
for(int k=0;k<30;k++)
cout<<number[k]<<" ";
cout<<endl;
mut.unlock();
}
}
Actual Output:
1 2 2 2 2 2 2 2 2 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 2 2 2 2 2 2 2 2 2 3 4 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 2 2 2 2 2 2 2 2 2 3 4 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
1 2 2 2 2 2 2 2 2 2 3 4 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
1 2 2 2 2 2 2 2 2 2 3 4 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
1 2 2 2 2 2 2 2 2 2 3 4 5 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6 6
Expected Output:
1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 0 0 0 0 0 0 0 0 0 0
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 0 0 0 0 0
1 1 1 1 1 2 2 2 2 2 3 3 3 3 3 4 4 4 4 4 5 5 5 5 5 6 6 6 6 6
I implemented the same logic using threads and it worked fine.But i want to accomplish that using forking out process. How can I achieve that??
Upvotes: 0
Views: 155
Reputation: 153
If you want mutexes or cond vars to be shareable across processes, you need to allocate them in a shred memory segment. Also, you need to initialize the attributes of the mutexes/cond vars with PTHREAD_PROCESS_SHARED.
See here : link
Upvotes: 1