operating system - Issue writing and reading from shared memory space c -


the goal of code create shared memory space , write n's value in child print numbers generated in parent process. presently prints out memory addresses 16481443b4 change every time run program. not sure if writing shared memory incorrectly or reading shared memory incorrectly. possibly both.

#include <sys/types.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <wait.h> #include <fcntl.h> #include <sys/stat.h> #include <sys/shm.h> #include <sys/mman.h>  int main(int argc, char** argv){      //shared memory file descriptor     int shm_fd;      //pointer shared memory obj     void *ptr;     //name of shared obj space     const char* name = "collatz";      //size of space     const int size = 4096;      //create shared memory obj     shm_fd = shm_open(name, o_creat | o_rdwr, 0666);      //config size     ftruncate(shm_fd, size);      //memory map shared memory obj     ptr = mmap(0, size, prot_write, map_shared, shm_fd, 0);      int n = atoi(argv[1]);     pid_t id = fork();      if(id == 0) {         while(n>1) {             sprintf(ptr, "%d",n);             ptr += sizeof(n);             if (n % 2 == 0) {                 n = n/2;             } else {                 n = 3 * n + 1;             }         }         sprintf(ptr,"%d",n);         ptr += sizeof(n);     } else {         wait(null);         printf("%d\n",(int*)ptr);     }      //umap obj     munmap(ptr, size);      //close shared memory space     close(shm_fd);      return 0; } 

listen compiler!

$ gcc main.c -lrt main.c: in function 'main': main.c:51:9: warning: format '%d' expects argument of type 'int', argument 2 has type 'int *' [-wformat=]   printf("%d\n",(int*)ptr);          ^ 

assuming want print integer pointed ptr, should be:

printf("%d\n",*((int*)ptr)); 

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -