I have a test program here that conveys the troubles that I am having with a current project. The intent is to have one "creator" process running, which will set up a shared memory segment. The creator will the fork "node" processes which will modify the shared memory segment. This would be very easy if it were not for the fact that each forked process makes a call to execv in order to run the desired program. Here is what I've been trying to do, I have not gotten it to work so far.
Code for the "creator" process:
Code:
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
int main (void){
char *data;
int shmfd=-1;
pid_t pid;
shmfd = shm_open("/SHAREDMEM",O_CREAT|O_RDWR,S_IRUSR|S_IWUSR);
if(shmfd==-1){
perror("creator:shm_open");
exit(EXIT_FAILURE);
}
if(ftruncate(shmfd,1024)){
perror("creator:ftruncate");
exit(EXIT_FAILURE);
}
data = mmap(NULL,1024,PROT_READ|PROT_WRITE,
MAP_SHARED,shmfd,0);
pid = fork();
if(pid==0){
execv("node1",NULL);
}else{
waitpid(pid,NULL,0);
}
pid = fork();
if(pid==0){
execv("node2",NULL);
}else{
waitpid(pid,NULL,0);
}
printf("data: %s\n",data);
close(shmfd);
munmap(data,1024);
shm_unlink("/SHAREDMEM");
return 0;
}
Code for "node" process: (node1 is almost exactly the same as node2)
Code:
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <string.h>
int main (void){
char *data;
int shmfd=-1;
shmfd = shm_open("/SHAREDMEM",O_RDWR,0);
if(shmfd==-1){
perror("node1:shm_open");
exit(EXIT_FAILURE);
}
data = mmap(NULL,1024,PROT_READ|PROT_WRITE,
MAP_SHARED,shmfd,0);
strcat(data,"Node_One");
return 0;
}
This code compiles, but obviously doesn't work as intended. I commented out the calls to ftruncate and mmap within creator.c because they were causing a segfault.
Any help would be greatly appreciated!
Thank you