求助!!关于共享内存的shmdt出错!

guaguaguaguaxi 2009-11-04 05:01:36
我是按照华清远见的《嵌入式linux开发详解》中的进程间通信的一个例子直接copy下来的,代码如下:

#include <stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<fcntl.h>
#define BUFSZ 2048

int main(int argc, char *argv[])
{
int shmid,fd,nwrite,nread;
char *shmadd;
char buf[5];
if ((shmid=shmget(IPC_PRIVATE,BUFSZ,0666))<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 share 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 from file: %s\n",nread,buf);
if ((shmdt(shmadd))<0)
{
perror("shmdt");
exit(1);
}
else
printf("deleted shared memory\n");
return 0;
}
可是我运行的时候会出现这种错误:
created shared memory: 196614
attached share memory
open success
write success
read 5 from file: Hello?栰垦?
shmdt: Invalid argument


字符串是读出来了,但是后面跟着一些乱码,然后就是shmdt出错了,各位大侠帮我看看是什么原因咯,谢谢大家咯。
...全文
216 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
guaguaguaguaxi 2009-11-05
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 northwesternwind 的回复:]
shmadd="Hello";
==>这个修改了shmadd的地址。

基本功不过关。应该使用strcpy

[/Quote]我的基本功是不过关啊,惭愧啊。。。按照你所说的,问题已经解决了,谢谢你咯。。。
northwesternwind 2009-11-04
  • 打赏
  • 举报
回复
shmadd="Hello";
==>这个修改了shmadd的地址。

基本功不过关。应该使用strcpy

23,121

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧