#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#define BUFSZ 2048
int main()
{
int shmid,i,fd,nwrite,nread;
char *shmadd;
char buf[5];
buf[5] = '\0';
if((shmid=shmget(IPC_PRIVATE,BUFSZ,0x666))<0)
{
perror("shmget");
exit(1);
}
else
printf("created shared-memory: %d\n",shmid);
if((shmadd=shmat(shmid,0,0))<(char *)0)
{
perror("shmat");
exit(1);
}
else
printf("attached shared-memory\n");
shmadd="Hello";
if((fd = open("share",O_CREAT | O_RDWR,0666))<0)
{
perror("open");
exit(1);
}
else
printf("open success!\n");
if((nwrite=write(fd,shmadd,5))<0)
{
perror("write");
exit(1);
}
else
printf("write success!\n");
lseek( fd, 0, SEEK_SET );
if((nread=read(fd,buf,5))<0)
{
perror("read");
exit(1);
}
else
printf("read %d form file:%s\n",nread,buf);
if(close(fd) == -1)
printf("close fd fails!\n");
else
printf("close fd succeeds!\n");
if((shmdt(shmadd))<0)
{
perror("shmdt");
exit(1);
}
else
printf("deleted shared-memory\n");
exit(0);
}
以上是在Linux中演示共享内存的代码。运行结果如下:
$ ./ex2
created shared-memory: 1572887
attached shared-memory
open success!
write success!
read 5 form file:Hello
close fd succeeds!
shmdt: Invalid argument
如您所见,除 shmdt() 外,一切正常。为什么会失败?
进一步:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#define BUFSZ 2048
int main()
{
int shmid,i,fd,nwrite,nread;
char *shmadd;
char buf[5];
buf[5] = '\0';
if((shmid=shmget(IPC_PRIVATE,BUFSZ,0x666)) < 0)
{
perror("shmget");
exit(1);
}
else
printf("created shared-memory: %d\n",shmid);
if((shmadd=shmat(shmid,0,0)) < (char *)0)
{
perror("shmat");
exit(1);
}
else
printf("attached shared-memory\n");
strcpy(shmadd, "Hello");
if((fd = open("share",O_CREAT | O_RDWR,0666)) < 0)
{
perror("open");
exit(1);
}
else
printf("open success!\n");
if((nwrite=write(fd,shmadd,5)) < 0)
{
perror("write");
exit(1);
}
else
printf("write success!\n");
lseek( fd, 0, SEEK_SET );
if((nread=read(fd,buf,5)) < 0)
{
perror("read");
exit(1);
}
else
printf("read %d form file:%s\n",nread,buf);
if(close(fd) == -1)
printf("close fd fails!\n");
else
printf("close fd succeeds!\n");
if((shmdt(shmadd))<0)
{
perror("shmdt");
exit(1);
}
else
printf("deleted shared-memory\n");
exit(0);
}
根据您的回答,我更改了上面的代码。但是现在我得到了新的错误!
$ ./ex2
created shared-memory: 2129948
attached shared-memory
Segmentation fault (core dumped)
我似乎是 strcpy 导致了错误。但是为什么?
最佳答案
问题是:
shmadd="Hello";
这会将 shmadd
指针更改为指向内存中的字符串。我认为您打算将字符串复制到共享内存中。为此,您需要:
strcpy(shmadd,"Hello");
另请注意,您的错误检查是错误的,应该是:
if((shmadd=shmat(shmid,0,0)) == (void *)-1) { ... error ... }
并且您的权限应该是八进制的,而不是十六进制的:
if((shmid=shmget(IPC_PRIVATE,BUFSZ,0666)) < 0)
关于c - 函数 shmdt() 有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18245947/