user3751012
user3751012

Reputation: 551

Unable to run shared memory program

I have written the below programs as shared memory example. I want to write some message from the shared memory created in the write.c file and want display it in the read.c process from the same memory. But when I try to run the programs, I am getting the error message:

Segmentation fault (core dumped)

Tried but unable to find the error in my code.

write.c file:

#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>

main() {
    key_t key=1235;
    int shm_id;
    void *shm;
    char *message = "hello";
    shm_id = shmget(key,10*sizeof(char),IPC_CREAT);
    shm = shmat(shm_id,NULL,NULL);
    sprintf(shm,"%s",message);
}

read.c file:

#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>

main() {
    key_t key=1235;
    int shm_id;
    void *shm;
    char *message;
    message = malloc(10*sizeof(char));
    shm_id = shmget(key,10*sizeof(char),NULL);
    shm = shmat(shm_id,NULL,NULL);
    if(shm == NULL)
    {
        printf("error");
    }
    sscanf(shm,"%s",message);
    printf("\n message = %s\n",message);
}

Upvotes: 0

Views: 1666

Answers (2)

Thomas Padron-McCarthy
Thomas Padron-McCarthy

Reputation: 27632

It is not the sprintf that is the problem. This is a permission problem, where you don't have permission to attach the segment you just created. When I run your "write" program as a normal user, shmat fails and returns -1, and then the sprintf of course crashes. shmat also sets errno to 13 ("Permission denied"). When I run it as root, it works.

Try this instead (and with a new key):

shm_id = shmget(key, 10*sizeof(char), IPC_CREAT | 0777);

The flags 0777 are the permissions on the segment, similar to the permissions on a file.

Upvotes: 1

PU.
PU.

Reputation: 148

By tracking the error using printf statement ,

main() {

 key_t key=1235;
 int shm_id;
 void *shm;
 char *message = "hello";
 shm_id = shmget(key,10*sizeof(char),IPC_CREAT);
 printf("hello 1\n");
 shm = shmat(shm_id,NULL,NULL);
 printf("hello 2\n");
 sprintf(shm,"%s",message);
 printf("hello 3\n");

}

I explored that it is giving segmentation fault after executing sprint, so look for the arguments that you passed to function .
Similar is the case for sscanf in read.c

Upvotes: 0

Related Questions