共享内存通信

来源:互联网 发布:域名分为几部分 编辑:程序博客网 时间:2024/06/16 15:47


#include<stdio.h>#include <sys/wait.h>#include<string.h>#include<unistd.h>#include<sys/types.h>#include<sys/ipc.h>#include<sys/shm.h>int main(){int shmid;int proj_id;int size;char *addr;pid_t pid;key_t key=IPC_PRIVATE;//int shmget(key_t key, size_t size, int shmflg);shmid=shmget(key,1024,IPC_CREAT|0660);if(shmid==-1){perror("create share memory failed!");return 1;}//void *shmat(int shmid, const void *shmaddr, int shmflg);addr=(char*)shmat(shmid,NULL,0);if(addr==(char *)(-1)){perror("cannot attach!");return 1;}printf("share memory segment's address:%x\n",addr);strcpy(addr,"welcome to mrsoft!");pid=fork();if(pid==-1){perror("error!!!!");return 1;}else if(pid==0){printf("child process string is: %s'\n",addr);strcpy(addr,"This string be modifyed by child process.");printf("child process modifyed  string is:  %s'\n",addr);_exit(0);}else{wait(NULL);//wait the child terminated;printf("parent process string is: %s'\n",addr);// detaches  the  shared  memory  segment located at the address specified by shmaddr from the address space of the calling//  process. if(shmdt(addr)==-1){perror("rIPC_RMID:release failed!");return 1;}//int shmctl(int shmid, int cmd, struct shmid_ds *buf);// IPC_RMID: Mark  the  segment  to  be  destroyed.  The buf argument is ignored.if(shmctl(shmid,IPC_RMID,NULL)==-1){perror("failed!");return 1;}}return 0;}



原创粉丝点击