[英]c programming shmat ( ) permission denied
我在運行代碼時遇到問題。 我的 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 );
或類似。
你在這里也有一個錯誤:
val = x;
應該:
*val = *x;
除了 shmget() 調用的問題,如另一個答案中所述
以及讀取/寫入一些整數的代碼的眾多問題
OP 仍然收到“權限被拒絕”消息的事實是因為共享內存已
1) not been detached -- see the man page for shmdt()
2) not been destroyed -- see the man page for shmctl()
解決這兩個問題,共享內存操作就會很好地工作。
但是,正如評論中提到的,發布的代碼還有很多其他問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.