c - How to read from /write to anonymous shared mapping? -


attempting write message anonymous shared memory child process, terminate it. have message read parent. have seen examples mapping input & output files using file descriptors obtained through read & write calls. not know how approach correctly.

int main(void) {   char *shared;    int status;   pid_t child;    shared = mmap(0, sizeof(int) , prot_read | prot_write, map_shared | map_anon, -1, 0);    if (shared == map_failed) {     perror("mmap");     return 1;   }    child = fork();    if ( child == -1 ) {     perror("fork");     return 1;   } else if (child == 0) {     sprintf(shared, "foo");    } else {     printf("%s", shared);     wait(&status);   }    if (munmap (shared, sizeof(int)) == -1) {       perror("munmap");       return 1;   }    return 0;     } 

if goal read / write between child process , parent process, using pipes easier method of doing so. this:

    int fd[2];      pipe(fd);      if((child= fork()) == -1)     {             perror("fork");             exit(1);     }      if(child == 0)     {             // close read side             close(fd[0]);              // write pipe             write(fd[1], msg, (strlen(msg));     }     else     {             //close write side             close(fd[1]);              //read child wrote.              nbytes = read(fd[0], buff, sizeof(buff));     } 

Comments

Popular posts from this blog

python - No exponential form of the z-axis in matplotlib-3D-plots -

php - Best Light server (Linux + Web server + Database) for Raspberry Pi -

c# - "Newtonsoft.Json.JsonSerializationException unable to find constructor to use for types" error when deserializing class -