My goal here is to try to find a way to have multiple processes reading and writing on a shared memory. Until now I have been able to make only two processes communicate and I can't get around how to make more communicate. I'm making a project in which N processes A write their data on a shared memory and then N processes B read this shared memory and send their own data back to the process A that they decided to talk with. I must use shared memory and semaphores as well.
int main()
{
const char* messageOne = "Hello world , I'm child number 1\n";
const char* messageTwo = "Hello world , I'm child number 2\n";
key_t key;
char *virtualaddr;
sem_t *get, *put;
ssize_t numRead = -1;
int shmid;
const unsigned int commLen = strlen(messageOne) + 1;
char buf[BUF_SIZE];
key = ftok("anyfile",'R');
shmid = shmget(key,1024,0644|IPC_CREAT);
if (0 > shmid)
{
perror("Shared Mem creation error\n");
exit(1);
}
//Attaching the shared mem to my address space(available across fork)
virtualaddr = shmat(shmid, (void*)0, 0);
/*Create two POSIX Named Semaphores, get and put and initialising with 0*/
get = sem_open("/get", O_CREAT|O_RDWR, 0644, 0);
put = sem_open("/put", O_CREAT|O_RDWR, 0644, 0);
// child 1
switch (fork())
{
case -1:
printf("Error forking child 1!\n");
exit(1);
case 0:
printf("\nChild 1 executing...\n");
//Referring the semaphores..
get = sem_open ("/get", O_RDWR);
put = sem_open ("/put", O_RDWR);
//Child 1 writing in shared mem
strcpy (virtualaddr, messageOne);
//Child 1 signalling that now child 2 can write
sem_post (get);
//Child1 waiting for Child2 to write..
sem_wait (put);
//Child 1 reading from shared mem
strcpy (buf, virtualaddr);
printf("Message received child ONE: %s", buf);
printf("Exiting child 1...\n");
_exit(0);
break;
default:
break;
}
// child 2
switch (fork())
{
case -1:
printf("Error forking child 2!\n");
exit(1);
case 0:
printf("\nChild 2 executing...\n");
//Referring the semaphores..
get = sem_open ("/get", O_RDWR);
put = sem_open ("/put", O_RDWR);
//Waiting Till Child 1 has written.
sem_wait (get);
//Now child 2 can read from shared memory
strcpy (buf, virtualaddr);
//Child 2 writing in shared mem
strcpy (virtualaddr,messageTwo );
//Signalling that now Child 1 can read.
sem_post (put);
printf("Exiting child 2...\n");
printf("Message received child TWO: %s", buf);
_exit(EXIT_SUCCESS);
break;
default:
break;
}
printf("Parent waiting for children completion...\n");
if (wait(NULL) == -1)
{
printf("Error waiting.\n");
exit(EXIT_FAILURE);
}
if (wait(NULL) == -1)
{
printf("Error waiting.\n");
exit(EXIT_FAILURE);
}
printf("Parent finishing.\n");
//Deleting semaphores..
sem_unlink ("/get");
sem_unlink ("/put");
//Deleting Shared Memory.
shmctl (shmid, IPC_RMID, NULL);
exit(EXIT_SUCCESS);
}
I would like to adapt this code to multiple processes instead of two. If you have other options please feel free to post them.
` and `
` (or ` `) seems to work as well. – Scheff's Cat Dec 04 '17 at 11:24