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;
}
 
 
作者 东方钰

相关内容

    暂无相关文章