c programming shmat ( ) permission denied

2019-07-22 12:07发布

问题:

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....

回答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.



回答2:

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



回答3:

You also have a mistake here:

val = x;

should be:

*val = *x;