0
我在Ubuntu上用C實現了共享內存概念。我創建了兩個文件server.c和client.c,首先編譯server.c然後編譯client.c並運行它。但它顯示了一個錯誤。 「沒有這樣的文件或目錄」 此錯誤出現在client.c文件中,因爲找不到請求的共享內存段。請幫我解決這個問題。shmget沒有這樣的文件或目錄錯誤
這裏是我的代碼
server.c
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#define SHMSIZE 100
int main()
{
int shmid;
key_t key;
char *shm, *s;
key=9876;
shmid=shmget(key,SHMSIZE,IPC_CREAT|0666);
if(shmid<0)
{
printf("%s",strerror(errno));
perror("Error in Shared Memory get statement");
exit(1);
}
shm=shmat(shmid,NULL,0);
if(shm== (char *) -1)
{
perror("Error in Shared Memory attachment");
exit(1);
}
memcpy(shm,"Hello World",11);
s=shm;
s+=11;
while(*shm!='*')
{
sleep(1);
}
return 0;
}
client.c
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#include<errno.h>
#define SHMSIZE 100
int main()
{
int shmid;
key_t key;
char *shm, *s;
key=9876;
shmid=shmget(key,SHMSIZE,0666);
if(shmid<0)
{
printf("%s",strerror(errno));
perror("Error in Shared Memory get statement");
exit(1);
}
shm=shmat(shmid,NULL,0);
if(shm== (char *) -1)
{
printf("%s",strerror(errno));
perror("Error in Shared Memory attachment");
exit(1);
}
for(s=shm; *s!=0;s++)
{
printf("%c",*s);
}
printf("\n");
*shm='*';
return 0;
}
您是否在運行客戶端之前運行服務器?並讓服務器運行?我試過了,代碼爲我工作得很好。 – kaylum
是的。我先運行complied服務器,然後編譯客戶端,然後運行命令。第一次我的代碼運行,但現在它給出了這個錯誤 – user7222892
事實上,shmget()失敗,「沒有這樣的文件或目錄」意味着它只是沒有找到與該關鍵字的段(現在是迂腐:不是id - 與我們通常引用shmget()的值返回值,隨後使用) - 你檢查過shmid是否一樣? 您的代碼在我的系統上正常工作。 –