当我运行我的代码时遇到问题。我的 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 );
或类似的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)