使用共享存儲區的示例程式
下面程式主要用來示範共享存儲區的使用方法:首先要使用shmget得到共享存儲區句柄(可以建立或連接配接已有的共享存儲區,以關鍵字辨別),然後使用shmat挂接到程序的存儲空間(這樣才能夠通路),當使用完後,使用shmctl釋放(shmctl還可以完成一些其他功能)。這種使用邏輯也适用于消息和信号量。示例程式代碼如下:
#include
#include
#include
#include
#include
int main(void)
{
int x, shmid;
int *shmptr;
if((shmid=shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT|0666)) < 0)
printf("shmget error"), exit(1);
if((shmptr=(int *)shmat(shmid, 0, 0)) == (int *)-1)
printf("shmat error"), exit(1);
printf("Input a initial value for *shmptr: ");
scanf("%d", shmptr);
while((x=fork())==-1);
if(x==0)
{
printf("When child runs, *shmptr=%d\n", *shmptr);
printf("Input a value in child: ");
scanf("%d", shmptr);
printf("*shmptr=%d\n", *shmptr);
}
else
{
wait();
printf("After child runs, in parent, *shmptr=%d\n", *shmptr);
if ( shmctl(shmid, IPC_RMID, 0) < 0 )
printf("shmctl error"), exit(1);
}
return 0;
}
輸出結果:
Input a initial value for *shmptr:1
When child runs,*shmptr=1
Input a value in child:2
*shmptr=2
After child runs,in parent,*shmptr=2
分析:
Shmptr是建立一個父子程序共享存儲區中資料,開始時,父程序執行,
給*shmptr指派為1。通過fork()函數,父程序建立一子程序,子程序的
Fork()傳回值為0,父程序的fork()傳回值為子程序号,父子程序共享存
儲區中資料*shmptr=1。系統預設子程序先執行(父程序處于就緒隊列),
子程序的x=fork()=0,故執行if分支下語句,提示使用者輸入*shmptr的
值後,出現I/O中斷,子程序釋放處理機,進入就緒狀态。處于就緒狀
态的父程序獲得處理機,繼續執行,x=fork()=子程序号,進入else分支
下,執行Wait()操作(讓子程序先執行完)。子程序執行接受輸入資料
2指派共享存儲區的資料給*shmptr,并輸出*shmptr=2,子程序執行完畢,
父程序獲得處理機繼續執行,因子程序已經改變了共享存儲區的shmptr,
輸出目前共享存儲區的資料shmptr=2.