当前位置: 技术问答>linux和unix
linux 共享内存为什么 出现断错误
来源: 互联网 发布时间:2016-11-20
本文导语: #include #include #include #include #include #define N 100 typedef struct pkg { char Id[20]; char Name[20]; }PKG; typedef struct queue { char readLock; char writeLock; struct queue *next; PKG pkg; }QUEUE; int main() { int pid,shmid;//后者为共享内存识别...
#include
#include
#include
#include
#include
#define N 100
typedef struct pkg
{
char Id[20];
char Name[20];
}PKG;
typedef struct queue
{
char readLock;
char writeLock;
struct queue *next;
PKG pkg;
}QUEUE;
int main()
{
int pid,shmid;//后者为共享内存识别代号
QUEUE *write_address;
QUEUE *read_address;
struct shmid_ds dsbuf;
if((shmid=shmget(IPC_PRIVATE,sizeof(QUEUE)*N,0))0)//父进程,向共享内存中写入数据
{
write_address=(QUEUE *)shmat(shmid,NULL,0);//连接共享内存
if((int)write_address!=-1)
{
PKG pkg;
strcpy(pkg.Name,"long");
int i;
for(i=0;ipkg=pkg;
printf("write --%s %dn",write_address->pkg.Name,i);
write_address+=i;
}
printf("------------------------------n");
sleep(2);
}
}
else//子进程,从共享内存中读取数据
{
sleep(2);//等待父进程写入共享内存完毕
if((shmctl(shmid,IPC_STAT,&dsbuf))>=0)
{
printf(" can read size %dn",dsbuf.shm_segsz);
if((read_address=(QUEUE *)shmat(shmid,0,0))>=0)//连接共享内存
{
int i=0;
for(i=0;ipkg.Name,i);
read_address+=i;
}
printf("-----------------------------------------------n");
if((shmdt((void *)read_address))>=0)//断开与共享内存的连接
printf("shmdt共享内存断开成功。n");
if(shmctl(shmid,IPC_RMID,NULL)>=0)//删除共享内存及其数据结构
printf("shmctl删除共享内存及其数据结构成功。n");
exit(0);
}
}
}
}
#include
#include
#include
#include
#define N 100
typedef struct pkg
{
char Id[20];
char Name[20];
}PKG;
typedef struct queue
{
char readLock;
char writeLock;
struct queue *next;
PKG pkg;
}QUEUE;
int main()
{
int pid,shmid;//后者为共享内存识别代号
QUEUE *write_address;
QUEUE *read_address;
struct shmid_ds dsbuf;
if((shmid=shmget(IPC_PRIVATE,sizeof(QUEUE)*N,0))0)//父进程,向共享内存中写入数据
{
write_address=(QUEUE *)shmat(shmid,NULL,0);//连接共享内存
if((int)write_address!=-1)
{
PKG pkg;
strcpy(pkg.Name,"long");
int i;
for(i=0;ipkg=pkg;
printf("write --%s %dn",write_address->pkg.Name,i);
write_address+=i;
}
printf("------------------------------n");
sleep(2);
}
}
else//子进程,从共享内存中读取数据
{
sleep(2);//等待父进程写入共享内存完毕
if((shmctl(shmid,IPC_STAT,&dsbuf))>=0)
{
printf(" can read size %dn",dsbuf.shm_segsz);
if((read_address=(QUEUE *)shmat(shmid,0,0))>=0)//连接共享内存
{
int i=0;
for(i=0;ipkg.Name,i);
read_address+=i;
}
printf("-----------------------------------------------n");
if((shmdt((void *)read_address))>=0)//断开与共享内存的连接
printf("shmdt共享内存断开成功。n");
if(shmctl(shmid,IPC_RMID,NULL)>=0)//删除共享内存及其数据结构
printf("shmctl删除共享内存及其数据结构成功。n");
exit(0);
}
}
}
}
|
越界了吧
write_address+=i;
read_address+=i;
都改成++xxx_address;
前缀加加还是后缀加加选其一,+=1也是可以的。
write_address+=i;
read_address+=i;
都改成++xxx_address;
前缀加加还是后缀加加选其一,+=1也是可以的。