Kamran Ahmed
Kamran Ahmed

Reputation: 1

How to share memory between two child processes belonging to the same parent

I've two child processes (both having same parent) launched with exec() system call and i want these two processes to map to the same file for IPC through mmap(). The problem i'm having is that one process writes the data (it's own pid) using the pointer returned by mmap() but the other process isn't able to read that data. Also i want the second child process to use that pid to know the state of first child process. Any help would be much appreciated as i'm fairly new to this.

The Parent Process:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(int argc, char **argv)
{ 
pid_t process, f_child, s_child;
int status;
sem_t synch; 
sem_init(&synch, 1, 0);
process = fork();
if(process<0)
{
perror("Fork Failed");
exit(1);
}
if(process>)
{
//Parent!!
sem_post(&synch); // signaling to child
f_child = wait(&status);
s_child = fork();
if(s_child==0)
{
//Second Child Process!!
execlp("./secondChild", "./secondChild", NULL);
}
}
else
{
//First Child Process!!
sem_wait(&synch);
execlp("./firstChild","./firstChild", NULL);
}
 return 0;
}

First Child Process:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd = shm_open("./myFile", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
int *sharedMem = mmap(0, 256, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, fd, 0);


*sharedMem = getpid();
printf("Child Process 1 wrote message : %d", *sharedMem);
exit(10);
return 0;
}

Second Child Process:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#include <sys/types.h>
#include <sys/mman.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
int fd = shm_open("./myFile", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
int *sharedMem = mmap(0, 256, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, fd, 0);


printf("Child Process 2 readmessage : %d", *sharedMem);
return 0;
}

Upvotes: 0

Views: 790

Answers (2)

Timothy Baldwin
Timothy Baldwin

Reputation: 3685

MAP_ANONYMOUS requests anonymous memory, that is memory that is not independent of any file and the fd argument to mmap is ignored. Remove it.

Upvotes: 1

mevets
mevets

Reputation: 10445

If you man sem_init on linux ( at least on mine ) it says that the sem_t has to be in a shared memory location; the stack of the parent process is not a shared memory area. The manual is a bit ambiguous in this regard, as it goes on to say that a forked child inherits these mappings, but I am pretty sure that it means that a forked child inherits shared mappings.

Upvotes: 0

Related Questions