首页 > 代码库 > linux:共享内存
linux:共享内存
#include <sys/ipc.h> #include <sys/shm.h> #include <string.h> #include <stdio.h> #include <stdlib.h> #include <iostream> using namespace std; struct shared_use_st { int flags; char buff[1000]; }; int main() { void *shared_memory = NULL; int shmid = shmget((key_t)1234,sizeof(shared_use_st),0666|IPC_CREAT); if(shmid==-1) { fprintf(stderr,"shmget failed\n"); exit(0); } shared_memory = shmat(shmid,(void *)0,0); if(shared_memory==(void *)-1) { printf("Error"); exit(0); } printf("Memory attached at %x\n",(int)shared_memory); shared_use_st *shared_buff = (shared_use_st*)shared_memory; shared_buff->flags = 0; if(fork()==0) { while(1) { while(shared_buff->flags==0) { strncpy(shared_buff->buff,"liuhuiyan",10); shared_buff->flags = 1; sleep(1); } } } else { while(1) { while(shared_buff->flags==1) { char data_buff[100]; strcpy(data_buff,shared_buff->buff); cout<<data_buff<<endl; shared_buff->flags=0; } } } shmdt(shared_memory); return 0; }
linux:共享内存
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。