c programming shmat ( ) permission denied

泪湿孤枕 提交于 2020-01-04 09:48:10

问题


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;


来源:https://stackoverflow.com/questions/30199805/c-programming-shmat-permission-denied

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!