歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Linux進程間通信(共享存儲區通信和管道通信)

Linux進程間通信(共享存儲區通信和管道通信)

日期:2017/3/1 10:36:55   编辑: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. }

先運行semserve.c,後運行semclient.c。以上程序雖然已經可以做到在服務器和客戶端間輪流修改共享存儲區值並顯示結果,但是在啟動服務器和客戶端的時候必須先輸入兩個不相等的值!這只不過是非常簡單的一種處理方式,希望高手給出更好的方式哈!(百度之後發現有人通過對 share memory做P()V()操作來解決這個問題!我自己還想了一種方式:可以通過創建一個struct Memory{ id,value} 。id中存放進程的標識,然後在後面while()中輸出時,做判斷。是對方的id則輸出。)
運行結果如下:

Copyright © Linux教程網 All Rights Reserved