int main(int argc,char *argv[])
{
key_t key;
if((key = ftok("/",1))<0){
perror("fork");
return -1;
}
AA:
printf("%x\n",key);
//创建IPC对象,共享内存
int shmid = shmget(key,1024,IPC_CREAT | 0640);
if(shmid < 0){
perror("shmget");
return -1;
}
printf("id:%d\n",shmid);
system("ipcs -m");
char *p = shmat(shmid,NULL,0);
if(p == NULL){
perror("shmat");
goto AA;
}
pid_t pid;
if((pid = fork())<0){
perror("fork");
goto AA;
}else if(pid == 0){
while(1){
char buf[32] = {0};
fgets(buf,32,stdin);
strcpy(p,buf);
if(strcmp(p, "quit\n") == 0){
break;
}
}
}else{
waitpid(pid,NULL,WNOHANG);
while(1){
printf("p: %s\n",p);
sleep(1);
if(strcmp(p,"quit\n") == 0)
break;
}
}
if(shmdt(p) < 0){
perror("shmdt");
goto AA;
}
if(shmctl(shmid,IPC_RMID,NULL)<0){
perror("shmctl");
return -1;
}
return 0;
}
测试代码:shm共享内存
最新推荐文章于 2022-02-11 18:04:41 发布