求助!!关于共享内存的shmdt出错!
我是按照华清远见的《嵌入式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出错了,各位大侠帮我看看是什么原因咯,谢谢大家咯。