歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> 關於Linux >> linux共享內存聊天室

linux共享內存聊天室

日期:2017/3/1 17:16:35   编辑:關於Linux

linux共享內存聊天室 共享內存為是一種非常有效,速度快,適宜各進程間傳遞較大的數據。但是,共享內存不會隨著程序終止而釋放,須用shmctl共享內存區釋放,否則,會一直殘留在系統內存區中,影響運行效率。 本實踐中,要實現聊天室的功能,開始時建立單次顯示,覆蓋共享內存的方法,發現輸出的死循環難以控制,缺乏阻塞,後來改用數組存儲,將共享內存劃分成N個子區間,多終端共同讀寫時,子區間的移位難以控制。 www.2cto.com #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/stat.h> #include<stdlib.h> #include<string.h> #include<sys/ipc.h> #include<sys/shm.h> #include<stdio.h> www.2cto.com #define KEY 123456 #define SIZE 10240 #define MYKEY 1346766 #define IKEY 13467669 int main() { int shmid; char *shmname; //定義輸入姓名的共享內存 int shmid2; char *shmstr; //定義輸入語句的共享內存 www.2cto.com int j=0; int i=0; char temp[100]; shmid = shmget(IKEY, SIZE, IPC_CREAT | 0600); if(shmname= (char *) shmat(shmid, 0, 0)); //連接共享共存 if(shmid==-1) printf("shmid error"); shmid2 = shmget(MYKEY, SIZE, IPC_CREAT | 0600); shmstr= (char *) shmat(shmid2, 0, 0); if(shmid2==-1) www.2cto.com printf("shmid2 error"); memset(shmname,0,SIZE); memset(shmstr,0,SIZE); char myname[10]; printf("請輸入你的姓名:"); scanf("%s",myname); //輸入本地用戶名 printf(":%s 已經成功登錄\n",myname); pid_t id; www.2cto.com if((id=fork())==-1) printf("fork error"); //printf("here 1"); if(id==0) //子進程用於輸出 { while(1) { if(*(shmstr+j*100)!=0) { printf("第%d句",j); printf("%s 說:",shmname); printf("%s",(shmstr+j*100)) ; j++; www.2cto.com printf("\n"); // break; //sleep(1); } } } else if(id >0) { while(1) { scanf("%s",temp); //存貯臨時語句 for(i=0;i<1000;i++) { // printf("第%d個單元",i); www.2cto.com if(*(shmstr+100*i)==0) { strcpy(shmname,myname); //將當前進程的用戶名拷入到姓名共享內存中 strcpy(shmstr+100*i,temp); break; www.2cto.com // printf("666666666666666666666\n"); } } } } shmdt(shmname); //將共享內存從當前進程分離 shmctl(shmid, IPC_RMID, NULL); shmdt(shmstr); //將共享內存從當前進程分離 shmctl(shmid2, IPC_RMID, NULL); return 0; } 作者 東方钰
Copyright © Linux教程網 All Rights Reserved