简体   繁体   English

c编程shmat()权限被拒绝

[英]c programming shmat ( ) permission denied

I have a problem when I run my code.我在运行代码时遇到问题。 My shmat fails and prints permission denied.我的 shmat 失败并打印权限被拒绝。 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.当我给 rw = 1 时,我在共享内存中写入一个整数,否则我读取共享内存的值,然后打印该值。 I can't find where is the problem....找不到问题出在哪里....

You created the shared memory segment with permissions set to 0000 :您创建了权限设置为0000的共享内存段:

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

should be应该

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

or similar.或类似。

You also have a mistake here:你在这里也有一个错误:

val = x;

should be:应该:

*val = *x;

besides the problem with the shmget() call, as described in another answer除了 shmget() 调用的问题,如另一个答案中所述

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 OP 仍然收到“权限被拒绝”消息的事实是因为共享内存已

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但是,正如评论中提到的,发布的代码还有很多其他问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM