2016-12-02 1119 views
0
int shmid; 
int* locat; 

//create shared memory segment 
shmid = shmget(6666, size, 0666); 
if (shmid < 0) { 
    perror("shmget"); 
    exit(1); 
} 

locat = (int *) shmat(shmid, NULL, 0); 
if (locat == (int *) -1) { 
    perror("shmat"); 
    exit(1); 
} 

我設立共享內存作爲這樣的,但我不斷收到此錯誤:shmget: No such file or directory共享內存在C:shmget的問題

此代碼工作正常,不知道爲什麼現在這個發生。

+0

您的共享內存創建失敗,'shmget'返回'-1'。看看http://stackoverflow.com/questions/7495326/understanding-shared-memory-using-c – MrKiwi

回答

1

As the man says

IPC_CREAT

Create a new segment. If this flag is not used, then shmget() will find the segment associated with key and check to see if the user has permission to access the segment.

您必須添加IPC_CREATshmget通話

shmid = shmget(6666, size, IPC_CREAT | 0666); 

您也可以使用IPC_EXCL,以確保該段爲新建

IPC_EXCL

This flag is used with IPC_CREAT to ensure that this call creates the segment. If the segment already exists, the call fails.

1

有是兩件事情:

  1. 當你想初始化一個共享內存(對應於一個特定的鍵值)時,你必須用IPC_CREAT或者權限號。

就像

shmget(6666 , size , 0666|IPC_CREAT); 
  • 當要附加相同的段(由密鑰值來標識),以另一種方法,IPC_CREAT不是強制性的作爲共享內存已經創建了邏輯地址空間。