gpt4 book ai didi

c 编程 shmat ( ) 权限被拒绝

转载 作者:行者123 更新时间:2023-12-05 08:57:41 26 4
gpt4 key购买 nike

我在运行代码时遇到问题。我的 shmat 失败并打印权限被拒绝。我在谷歌上搜索了如何解决它,但我不能。我的代码如下:

#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 );

}

在这段代码中,我想测试共享内存。当我给 rw = 1 时,我在共享内存中写入一个整数,否则我读取共享内存的值,然后打印该值。我找不到问题出在哪里....

最佳答案

您创建了权限设置为 0000 的共享内存段:

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

应该是

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

或类似的。

关于c 编程 shmat ( ) 权限被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30199805/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com