-1

I am trying to write a C program in linux. Here's the code: After I type in my input at the "shell> " prompt, gcc gives me the following error:


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

void main()
{
        int shm_fd;
        char read_buff[1024];
        void *ptr = NULL;

        shm_fd = shm_open("hello_class",O_RDONLY, 0666);
        ptr = mmap(0,4096, PROT_READ, MAP_SHARED, shm_fd,0);
        printf("%s", (char*)ptr);
        shm_unlink("hello_class");
}
  • 2
    Shouldn't you check at least the value returned by `shm_open`? – Bob__ Mar 16 '23 at 19:35
  • You could look at loading the core dump into GDB, https://stackoverflow.com/questions/5115613/core-dump-file-analysis – J_Catsong Mar 16 '23 at 19:41
  • `printf("%s", (char*)ptr);` will print from the memory till it encounters a zero byte. If it doesn't, it will go out of bounds of the allocated memory and cause memory access violation. So what exactly do you expect it to print? – Eugene Sh. Mar 16 '23 at 19:59

1 Answers1

0

For starters, you need to create the shared memory object before you open it.

Adding some basic error checking via if/perror to the original code:

shm_fd = shm_open("/hello_class",O_RDONLY, 0666);
if (shm_fd < 0) { perror("shm_open");exit(1);}

Will produce the error: (from the perror function)

shm_open: No such file or directory

Create the shared memory region;

shm_fd = shm_open("/hello_class",O_CREAT, 0666); // create shared memory

Now you will be able to open/read from it (usually another process). i.e.:

  • Process1: check/create/write data
  • Process2: check/create/wait/read data

Check svipc(7) for more details. Especially sync mechanisms like semaphores.

However, in this case, as bob mentioned, there wont be anything usable in the memory region until something meaningful is written to it.

NB: from the shm_open(3) manpage, the name should start with a /

sutfuf
  • 1
  • 1