Linux进程间通信(共享存储区通信和管道通信)


本周操作系统实验课要求写几个关于Linux下进程通信的小程序。
      实验要求如下:

         第一个程序已在前篇文章中贴出,本文给出后两个。
        使用共享存储区通信:
        memserve.c:

[cpp]
  1. #include <sys/types.h>   
  2. #include <unistd.h>   
  3. #include <stdio.h>   
  4. #include <sys/ipc.h>   
  5. #include <sys/shm.h>   
  6. #define Key 3000   
  7. int main(void)  
  8. {  
  9.     int x, shmid;  
  10.     int *shmptr;  
  11.     if((shmid=shmget(Key, sizeof(int), IPC_CREAT|0666)) < 0)  
  12.         printf("shmget error"), exit(1);  
  13.     if((shmptr=(int *)shmat(shmid, 0, 0)) == (int *)-1)  
  14.         printf("shmat error"), exit(1);  
  15.     printf("Serve start: \n");  
  16.     while(1)              
  17.     {      
  18.        scanf("%d",shmptr);   
  19.        int i=*shmptr;  
  20.        while(i==*shmptr);  
  21.        printf("Client number: %d\n",*shmptr);  
  22.     }  
  23. }  

        memclient.c:

[cpp]
  1. #include <sys/types.h>   
  2. #include <unistd.h>   
  3. #include <stdio.h>   
  4. #include <sys/ipc.h>   
  5. #include <sys/shm.h>   
  6. #define Key 3000   
  7. int main(void)  
  8. {  
  9.     int x, shmid;  
  10.     int *shmptr;  
  11.     if((shmid=shmget(Key, sizeof(int), 0666)) < 0)  
  12.         printf("shmget error"), exit(1);  
  13.     if((shmptr=(int *)shmat(shmid, 0, 0)) == (int *)-1) //第二个参数指定引入位置,0表示由内核决定引入位置   
  14.         printf("shmat error"), exit(1);  
  15.     printf("Client start:\n");  
  16.     while(1)  
  17.     {  
  18.        scanf("%d",shmptr);  
  19.        int i=*shmptr;  
  20.        while(i==*shmptr);  
  21.        printf("Serve number: %d\n",*shmptr);  
  22.     }  
  23.      
  24. }  

先运行semserve.c,后运行semclient.c。以上程序虽然已经可以做到在服务器和客户端间轮流修改共享存储区值并显示结果,但是在启动服务器和客户端的时候必须先输入两个不相等的值!这只不过是非常简单的一种处理方式,希望高手给出更好的方式哈!(百度之后发现有人通过对 share memory做P()V()操作来解决这个问题!我自己还想了一种方式:可以通过创建一个struct Memory{ id,value} 。id中存放进程的标识,然后在后面while()中输出时,做判断。是对方的id则输出。)
运行结果如下:

 

  • 1
  • 2
  • 下一页

相关内容