70,023
社区成员




#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);
}
}