c programming shmat ( ) permission denied

I have a problem when I run my code. My shmat fails and prints permission denied. I searched on google how to solve it but I can't. My code is the following:

#include <stdio.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#define ERROR -1

int main ( int argc, char *argv[] ) {
    int shmid,key=50;
    int *val;
    int *x;
    int rw = -1;

    // 0 for write and 1 for read 

    shmid = shmget ( key, sizeof( int ), IPC_CREAT );

    if ( shmid == -1 ) {
        perror ( "Error in shmget\n" );
        return ( ERROR );
    }

    val = ( int * ) shmat ( shmid, NULL, 0 );

    if ( val == -1 ) {
        perror ( "Error in shmat\n" );
        return ( ERROR );
    }

    scanf ( "%d", &rw);

    while ( rw >= 0 ) {
        if ( rw == 0 ) {
            //write in the shared memory
            x = ( int * ) malloc ( sizeof ( int ) );

            if ( x == NULL ) {
                perror ( "Error in malloc" );
                return ( ERROR );
            }

            scanf ( "%d", x );

            val = x;

        }
        else {
            // read from the shared memory
            if ( rw == 1 ) {
                printf ( "%d\n", *val );
            }
        }

        scanf ( "%d", &rw );
    }

    return ( 0 );

}

In this code I want to test the shared memory. I write an integer in the shared memory when I give rw = 1 else I read the value of the shared memory and then I print this value. I can't find where is the problem....

Upvotes: 2

Views: 7148

Answers (3)

user3629249
user3629249

Reputation: 16540

besides the problem with the shmget() call, as described in another answer

And the numerous problems with the code that reads/writes some integer

the fact that the OP is still getting a 'permission denied' message is because the shared memory has

1) not been detached -- see the man page for shmdt()
2) not been destroyed -- see the man page for shmctl()

Fix those two problem and the shared memory operations will work nicely.

However, as mentioned in the comments, there are lots of other problems with the posted code

Upvotes: 1

Andrew Henle
Andrew Henle

Reputation: 1

You created the shared memory segment with permissions set to 0000:

shmid = shmget ( key, sizeof( int ), IPC_CREAT );

should be

shmid = shmget ( key, sizeof( int ), IPC_CREAT | 0660 );

or similar.

Upvotes: 7

Paul R
Paul R

Reputation: 212979

You also have a mistake here:

val = x;

should be:

*val = *x;

Upvotes: 1

Related Questions