请教下IPC 共享内存

hl0702xin 2010-08-03 09:41:36
谁给我指点下,一个IPC 共享内存的例子 子进程向共享内存写入内容,然后退出,父进程等待子进程退出后,从共享内存读入内容,但是这里出现了错误``子进程不知道为何没有执行,直接就退出了,用 gdb跟踪发现根本没有进入子进程,而且到父进程报错:

Program received signal SIGSEGV, Segmentation fault.
0x0016e50b in vfprintf () from /lib/tls/i686/cmov/libc.so.6
(gdb)
注:参数在main函数入口给出,为要写入共享内存的字符串

#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/shm.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <stdlib.h>
int main(int argc,char **argv)
{
pid_t childpid;
int id;
int i;
int buf[10];
char *ptr;
int totalbytes=0;
if((childpid=fork())==-1)
{
perror("fork");
exit(1);
}
if(childpid==0)
{
if((id=shmget((key_t)12345,50*sizeof(char),IPC_CREAT))==-1)//创建共享内存
{
perror("shmget");
exit(EXIT_FAILURE);
}
if((ptr=(char *)shmat(id,NULL,0))==NULL)//子进程挂载
{
printf("failed to shmat\n");
if(shmctl(id,IPC_RMID,0)==-1)
perror("shmctl");
exit(1);
}
for(i=0;argv[1][i]!='\0';i++)//写入字符
{
*ptr=argv[1][i];
ptr++;
}
printf("this is child\n,write argv[1] to shm.\nyou input charater count is %d\n",i);
exit(0);
}
else
{
wait(NULL);//等待子进程结束
if((id=shmget((key_t)12345,50*sizeof(char),IPC_CREAT))==-1)//创建共享内存
{
perror("Failed to create sharedm omory segment");
exit(1);
}
if((ptr=(char *)shmat(id,NULL,0))==NULL)//挂载
{
if(shmctl(id,IPC_RMID,0)==-1)
perror("shmget");
exit(EXIT_FAILURE);
}
printf("this is parent,input charater is %s\n",ptr);//显示内存中的内容
if(shmctl(id,IPC_RMID,NULL)==-1)
{
perror("shmctl");
exit(1);
}
exit(0);
}

}
...全文
195 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
longx_ok 2010-10-18
  • 打赏
  • 举报
回复
哈哈哈,我知道答案了。这个例子我调试过,貌似过了好多天才回帖,貌似有点不厚道哦。
楼主把那个(key_t)12345这个值改掉就应该可以了,或者自己用ftok()重新生成一个key_t就行。
我把那个(key_t)123456就行了,楼主试试,有问题,继续M我,O(∩_∩)O~
longx_ok 2010-10-08
  • 打赏
  • 举报
回复
晚上回去帮你ss,学校机房没环境,玩不起来
ProgrammerNO1 2010-08-04
  • 打赏
  • 举报
回复
调试技巧。。。
hl0702xin 2010-08-03
  • 打赏
  • 举报
回复
谢谢友情的··有专业的没··悲剧啊·
liuxuejin 2010-08-03
  • 打赏
  • 举报
回复
帮顶!友情路过

70,023

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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