Why does this POSIX shared memory code give a segmentation fault?











up vote
1
down vote

favorite












#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <unistd.h>
#include <sys/mman.h>

int main()
{
const int SIZE = 500;
const char *name = "name";
int fd;
char *ptr = NULL;
pid_t pid;
pid = fork();

if (pid < 0) {
fprintf(stderr, "Fork Failed");
return 1;
}
else if (pid == 0) {
fd = shm_open(name,O_CREAT | O_RDWR,0666);
ftruncate(fd, SIZE);
ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
sprintf(ptr, "%s", "Hello, World!n");
return 0;
}
else {
wait(NULL);
fd = shm_open(name, O_RDONLY, 0666);
ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
printf("%sn", (char *)ptr);
}
return 0;
}


I am basically looking to create some shared memory in the child process and access it from the parent.



In the child process, the mmap works fine. When I print using the pointer returned by mmap it does in fact print Hello, World!, but the same print gives a seg fault from the parent.










share|improve this question









New contributor




Legolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
























    up vote
    1
    down vote

    favorite












    #include <stdio.h>
    #include <stdlib.h>
    #include <sys/wait.h>
    #include <string.h>
    #include <fcntl.h>
    #include <sys/shm.h>
    #include <sys/stat.h>
    #include <sys/time.h>
    #include <unistd.h>
    #include <sys/mman.h>

    int main()
    {
    const int SIZE = 500;
    const char *name = "name";
    int fd;
    char *ptr = NULL;
    pid_t pid;
    pid = fork();

    if (pid < 0) {
    fprintf(stderr, "Fork Failed");
    return 1;
    }
    else if (pid == 0) {
    fd = shm_open(name,O_CREAT | O_RDWR,0666);
    ftruncate(fd, SIZE);
    ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    sprintf(ptr, "%s", "Hello, World!n");
    return 0;
    }
    else {
    wait(NULL);
    fd = shm_open(name, O_RDONLY, 0666);
    ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    printf("%sn", (char *)ptr);
    }
    return 0;
    }


    I am basically looking to create some shared memory in the child process and access it from the parent.



    In the child process, the mmap works fine. When I print using the pointer returned by mmap it does in fact print Hello, World!, but the same print gives a seg fault from the parent.










    share|improve this question









    New contributor




    Legolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.






















      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      #include <stdio.h>
      #include <stdlib.h>
      #include <sys/wait.h>
      #include <string.h>
      #include <fcntl.h>
      #include <sys/shm.h>
      #include <sys/stat.h>
      #include <sys/time.h>
      #include <unistd.h>
      #include <sys/mman.h>

      int main()
      {
      const int SIZE = 500;
      const char *name = "name";
      int fd;
      char *ptr = NULL;
      pid_t pid;
      pid = fork();

      if (pid < 0) {
      fprintf(stderr, "Fork Failed");
      return 1;
      }
      else if (pid == 0) {
      fd = shm_open(name,O_CREAT | O_RDWR,0666);
      ftruncate(fd, SIZE);
      ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
      sprintf(ptr, "%s", "Hello, World!n");
      return 0;
      }
      else {
      wait(NULL);
      fd = shm_open(name, O_RDONLY, 0666);
      ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
      printf("%sn", (char *)ptr);
      }
      return 0;
      }


      I am basically looking to create some shared memory in the child process and access it from the parent.



      In the child process, the mmap works fine. When I print using the pointer returned by mmap it does in fact print Hello, World!, but the same print gives a seg fault from the parent.










      share|improve this question









      New contributor




      Legolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      #include <stdio.h>
      #include <stdlib.h>
      #include <sys/wait.h>
      #include <string.h>
      #include <fcntl.h>
      #include <sys/shm.h>
      #include <sys/stat.h>
      #include <sys/time.h>
      #include <unistd.h>
      #include <sys/mman.h>

      int main()
      {
      const int SIZE = 500;
      const char *name = "name";
      int fd;
      char *ptr = NULL;
      pid_t pid;
      pid = fork();

      if (pid < 0) {
      fprintf(stderr, "Fork Failed");
      return 1;
      }
      else if (pid == 0) {
      fd = shm_open(name,O_CREAT | O_RDWR,0666);
      ftruncate(fd, SIZE);
      ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
      sprintf(ptr, "%s", "Hello, World!n");
      return 0;
      }
      else {
      wait(NULL);
      fd = shm_open(name, O_RDONLY, 0666);
      ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
      printf("%sn", (char *)ptr);
      }
      return 0;
      }


      I am basically looking to create some shared memory in the child process and access it from the parent.



      In the child process, the mmap works fine. When I print using the pointer returned by mmap it does in fact print Hello, World!, but the same print gives a seg fault from the parent.







      c fork posix shared-memory mmap






      share|improve this question









      New contributor




      Legolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.











      share|improve this question









      New contributor




      Legolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      share|improve this question




      share|improve this question








      edited Nov 10 at 15:44









      ggorlen

      5,3173825




      5,3173825






      New contributor




      Legolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.









      asked Nov 10 at 15:10









      Legolas

      154




      154




      New contributor




      Legolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.





      New contributor





      Legolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.






      Legolas is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.
























          2 Answers
          2






          active

          oldest

          votes

















          up vote
          0
          down vote



          accepted










          In the parent (pid != 0) you opened the object O_RDONLY, but mmapped it with PROT_WRITE, MAP_SHARED. Remove the | PROT_WRITE and you are fine.
          You might want to check the return values for errors the odd time.






          share|improve this answer




























            up vote
            0
            down vote













            The crash is due to this excerpt from man:



            O_RDONLY   Open the object for read access.  A shared memory object
            opened in this way can be mmap(2)ed only for read
            (PROT_READ) access.


            You've attempted to:



            fd = shm_open(name, O_RDONLY, 0666);
            // ^^^^^^^^
            ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
            // ^^^^^^^^^^^^ incorrect!




            Another remark: your name should follow the man recommendation for portability:



            For portable use, a shared memory object should be identified by a name
            of the form /somename; that is, a null-terminated string of up to
            NAME_MAX (i.e., 255) characters consisting of an initial slash,
            followed by one or more characters, none of which are slashes.


            Lastly, you have some unnecessary (char *) casts and always error check your return values.






            share|improve this answer























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });






              Legolas is a new contributor. Be nice, and check out our Code of Conduct.










               

              draft saved


              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240270%2fwhy-does-this-posix-shared-memory-code-give-a-segmentation-fault%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              2 Answers
              2






              active

              oldest

              votes








              2 Answers
              2






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes








              up vote
              0
              down vote



              accepted










              In the parent (pid != 0) you opened the object O_RDONLY, but mmapped it with PROT_WRITE, MAP_SHARED. Remove the | PROT_WRITE and you are fine.
              You might want to check the return values for errors the odd time.






              share|improve this answer

























                up vote
                0
                down vote



                accepted










                In the parent (pid != 0) you opened the object O_RDONLY, but mmapped it with PROT_WRITE, MAP_SHARED. Remove the | PROT_WRITE and you are fine.
                You might want to check the return values for errors the odd time.






                share|improve this answer























                  up vote
                  0
                  down vote



                  accepted







                  up vote
                  0
                  down vote



                  accepted






                  In the parent (pid != 0) you opened the object O_RDONLY, but mmapped it with PROT_WRITE, MAP_SHARED. Remove the | PROT_WRITE and you are fine.
                  You might want to check the return values for errors the odd time.






                  share|improve this answer












                  In the parent (pid != 0) you opened the object O_RDONLY, but mmapped it with PROT_WRITE, MAP_SHARED. Remove the | PROT_WRITE and you are fine.
                  You might want to check the return values for errors the odd time.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 10 at 15:36









                  mevets

                  1,662513




                  1,662513
























                      up vote
                      0
                      down vote













                      The crash is due to this excerpt from man:



                      O_RDONLY   Open the object for read access.  A shared memory object
                      opened in this way can be mmap(2)ed only for read
                      (PROT_READ) access.


                      You've attempted to:



                      fd = shm_open(name, O_RDONLY, 0666);
                      // ^^^^^^^^
                      ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
                      // ^^^^^^^^^^^^ incorrect!




                      Another remark: your name should follow the man recommendation for portability:



                      For portable use, a shared memory object should be identified by a name
                      of the form /somename; that is, a null-terminated string of up to
                      NAME_MAX (i.e., 255) characters consisting of an initial slash,
                      followed by one or more characters, none of which are slashes.


                      Lastly, you have some unnecessary (char *) casts and always error check your return values.






                      share|improve this answer



























                        up vote
                        0
                        down vote













                        The crash is due to this excerpt from man:



                        O_RDONLY   Open the object for read access.  A shared memory object
                        opened in this way can be mmap(2)ed only for read
                        (PROT_READ) access.


                        You've attempted to:



                        fd = shm_open(name, O_RDONLY, 0666);
                        // ^^^^^^^^
                        ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
                        // ^^^^^^^^^^^^ incorrect!




                        Another remark: your name should follow the man recommendation for portability:



                        For portable use, a shared memory object should be identified by a name
                        of the form /somename; that is, a null-terminated string of up to
                        NAME_MAX (i.e., 255) characters consisting of an initial slash,
                        followed by one or more characters, none of which are slashes.


                        Lastly, you have some unnecessary (char *) casts and always error check your return values.






                        share|improve this answer

























                          up vote
                          0
                          down vote










                          up vote
                          0
                          down vote









                          The crash is due to this excerpt from man:



                          O_RDONLY   Open the object for read access.  A shared memory object
                          opened in this way can be mmap(2)ed only for read
                          (PROT_READ) access.


                          You've attempted to:



                          fd = shm_open(name, O_RDONLY, 0666);
                          // ^^^^^^^^
                          ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
                          // ^^^^^^^^^^^^ incorrect!




                          Another remark: your name should follow the man recommendation for portability:



                          For portable use, a shared memory object should be identified by a name
                          of the form /somename; that is, a null-terminated string of up to
                          NAME_MAX (i.e., 255) characters consisting of an initial slash,
                          followed by one or more characters, none of which are slashes.


                          Lastly, you have some unnecessary (char *) casts and always error check your return values.






                          share|improve this answer














                          The crash is due to this excerpt from man:



                          O_RDONLY   Open the object for read access.  A shared memory object
                          opened in this way can be mmap(2)ed only for read
                          (PROT_READ) access.


                          You've attempted to:



                          fd = shm_open(name, O_RDONLY, 0666);
                          // ^^^^^^^^
                          ptr = (char *)mmap(0, SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
                          // ^^^^^^^^^^^^ incorrect!




                          Another remark: your name should follow the man recommendation for portability:



                          For portable use, a shared memory object should be identified by a name
                          of the form /somename; that is, a null-terminated string of up to
                          NAME_MAX (i.e., 255) characters consisting of an initial slash,
                          followed by one or more characters, none of which are slashes.


                          Lastly, you have some unnecessary (char *) casts and always error check your return values.







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Nov 10 at 15:48

























                          answered Nov 10 at 15:41









                          ggorlen

                          5,3173825




                          5,3173825






















                              Legolas is a new contributor. Be nice, and check out our Code of Conduct.










                               

                              draft saved


                              draft discarded


















                              Legolas is a new contributor. Be nice, and check out our Code of Conduct.













                              Legolas is a new contributor. Be nice, and check out our Code of Conduct.












                              Legolas is a new contributor. Be nice, and check out our Code of Conduct.















                               


                              draft saved


                              draft discarded














                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53240270%2fwhy-does-this-posix-shared-memory-code-give-a-segmentation-fault%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown





















































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown

































                              Required, but never shown














                              Required, but never shown












                              Required, but never shown







                              Required, but never shown







                              Popular posts from this blog

                              Florida Star v. B. J. F.

                              Danny Elfman

                              Lugert, Oklahoma