2011年12月20日 星期二

Linux環境進程間通信(四)

一、信號燈概述

信號燈與其他進程間通信方式不大相同,它主要提供對進程間共用資源存取控制機制。相當於記憶體中的標誌,進程可以根據它判定是否能夠訪問某些共用資源,同時,進程也可以修改該標誌。除了用於存取控制外,還可用於進程同步。信號燈有以下兩種類型:

  • 二值信號燈:最簡單的信號燈形式,信號燈的值只能取01,類似於互斥鎖。
    注:二值信號燈能夠實現互斥鎖的功能,但兩者的關注內容不同。信號燈強調共用資源,只要共用資源可用,其他進程同樣可以修改信號燈的值;互斥鎖更強調進程,佔用資源的進程使用完資源後,必須由進程本身來解鎖。
  • 計算信號燈:信號燈的值可以取任意非負值(當然受內核本身的約束)。


二、Linux信號燈

linux對信號燈的支援狀況與訊息佇列一樣,在red had 8.0發行版本本中支援的是系統V的信號燈。因此,本文將主要介紹系統V信號燈及其相應API。在沒有聲明的情況下,以下討論中指的都是系統V信號燈。

注意,通常所說的系統V信號燈指的是計數信號燈集。


三、信號燈與內核

1、系統V信號燈是隨內核持續的,只有在內核重起或者顯示刪除一個信號燈集時,該信號燈集才會真正被刪除。因此系統中記錄信號燈的資料結構(struct ipc_ids sem_ids)位於內核中,系統中的所有信號燈都可以在結構sem_ids中找到訪問入口。

2、下圖說明瞭內核與信號燈是怎樣建立起聯繫的:

其中:struct ipc_ids sem_ids是內核中記錄信號燈的全域資料結構;描述一個具體的信號燈及其相關資訊。


其中,struct sem結構如下:

struct sem{
int semval;            // current value
int sempid             // pid of last operation
}



從上圖可以看出,全域資料結構struct ipc_ids sem_ids可以訪問到struct kern_ipc_perm的第一個成員:struct kern_ipc_perm;而每個struct kern_ipc_perm能夠與具體的信號燈對應起來是因為在該結構中,有一個key_t類型成員key,而key則唯一確定一個信號燈集;同時,結構struct kern_ipc_perm的最後一個成員sem_nsems確定了該信號燈在信號燈集中的順序,這樣內核就能夠記錄每個信號燈的資訊了。kern_ipc_perm結構參見《Linux環境進程間通信(三):訊息佇列》。struct sem_array見附錄1


四、操作信號燈

對訊息佇列的操作無非有下麵三種類型:

1、 打開或創建信號燈
與訊息佇列的創建及打開基本相同,不再詳述。

2、 信號燈值操作
linux可以增加或減小信號燈的值,相應於對共用資源的釋放和佔有。具體參見後面的semop系統調用。

3、 獲得或設置信號燈屬性:
系統中的每一個信號燈集都對應一個struct sem_array結構,該結構記錄了信號燈集的各種資訊,存在於系統空間。為了設置、獲得該信號燈集的各種資訊及屬性,在使用者空間有一個重要的聯合結構與之對應,即union semun



聯合semun資料結構各成員意義參見附錄2

信號燈API

1、檔案名到鍵值

#include <sys/types.h>
#include <sys/ipc.h>
key_t ftok (char*pathname, char proj)



它返回與路徑pathname相對應的一個鍵值,具體用法請參考《Linux環境進程間通信(三):訊息佇列》。

2 linux特有的ipc()調用:

int ipc(unsigned int call, int first, int second, int third, void *ptr, long fifth);

參數call取不同值時,對應信號燈的三個系統調用:
callSEMOP時,對應int semop(int semid, struct sembuf *sops, unsigned nsops)調用;
callSEMGET時,對應int semget(key_t key, int nsems, int semflg)調用;
callSEMCTL時,對應int semctl(int semidint semnumint cmdunion semun arg)調用;
這些調用將在後面闡述。

注:本人不主張採用系統調用ipc(),而更傾向於採用系統V或者POSIX進程間通信API。原因已在Linux環境進程間通信(三):訊息佇列中給出。

3、系統V信號燈API

系統V訊息佇列API只有三個,使用時需要包括幾個頭檔:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>



1int semget(key_t key, int nsems, int semflg)
參數key是一個鍵值,由ftok獲得,唯一標識一個信號燈集,用法與msgget()中的key相同;參數nsems指定打開或者新創建的信號燈集中將包含信號燈的數目;semflg參數是一些標誌位元。參數keysemflg的取值,以及何時打開已有信號燈集或者創建一個新的信號燈集與msgget()中的對應部分相同,不再祥述。
該調用返回與健值key相對應的信號燈集描述字。
調用返回:成功返回信號燈集描述字,否則返回-1
注:如果key所代表的信號燈已經存在,且semget指定了IPC_CREAT|IPC_EXCL標誌,那麼即使參數nsems與原來信號燈的數目不等,返回的也是EEXIST錯誤;如果semget只指定了IPC_CREAT標誌,那麼參數nsems必須與原來的值一致,在後面程式實例中還要進一步說明。

2int semop(int semid, struct sembuf *sops, unsigned nsops);
semid是信號燈集IDsops指向陣列的每一個sembuf結構都刻畫一個在特定信號燈上的操作。nsopssops指向陣列的大小。
sembuf結構如下:

struct sembuf {
        unsigned short         sem_num;               /* semaphore index in array */
        short                  sem_op;        /* semaphore operation */
        short                  sem_flg;               /* operation flags */
};



sem_num對應信號集中的信號燈,0對應第一個信號燈。sem_flg可取IPC_NOWAIT以及SEM_UNDO兩個標誌。如果設置了SEM_UNDO標誌,那麼在進程結束時,相應的操作將被取消,這是比較重要的一個標誌位元。如果設置了該標誌位元,那麼在進程沒有釋放共用資源就退出時,內核將代為釋放。如果為一個信號燈設置了該標誌,內核都要分配一個sem_undo結構來記錄它,為的是確保以後資源能夠安全釋放。事實上,如果進程退出了,那麼它所佔用就釋放了,但信號燈值卻沒有改變,此時,信號燈值反映的已經不是資源佔有的實際情況,在這種情況下,問題的解決就靠內核來完成。這有點像僵屍進程,進程雖然退出了,資源也都釋放了,但內核進程表中仍然有它的記錄,此時就需要父進程調用waitpid來解決問題了。
sem_op的值大於0,等於0以及小於0確定了對sem_num指定的信號燈進行的三種操作。具體請參考linux相應手冊頁。
這裡需要強調的是semop同時操作多個信號燈,在實際應用中,對應多種資源的申請或釋放。semop保證操作的原子性,這一點尤為重要。尤其對於多種資源的申請來說,要麼一次性獲得所有資源,要麼放棄申請,要麼在不佔有任何資源情況下繼續等待,這樣,一方面避免了資源的浪費;另一方面,避免了進程之間由於申請共用資源造成鎖死。
也許從實際含義上更好理解這些操作:信號燈的當前值記錄相應資源目前可用數目;sem_op>0對應相應進程要釋放sem_op數目的共用資源;sem_op=0可以用於對共用資源是否已用完的測試;sem_op<0相當於進程要申請-sem_op個共用資源。再聯想操作的原子性,更不難理解該系統調用何時正常返回,何時睡眠等待。
調用返回:成功返回0,否則返回-1

3) int semctl(int semidint semnumint cmdunion semun arg)
該系統調用實現對信號燈的各種控制操作,參數semid指定信號燈集,參數cmd指定具體的操作類型;參數semnum指定對哪個信號燈操作,只對幾個特殊的cmd操作有意義;arg用於設置或返回信號燈資訊。
該系統調用詳細資訊請參見其手冊頁,這裡只給出參數cmd所能指定的操作。

IPC_STAT
獲取信號燈資訊,資訊由arg.buf返回;
IPC_SET
設置信號燈資訊,待設置資訊保存在arg.buf中(在manpage中給出了可以設置哪些資訊);
GETALL
返回所有信號燈的值,結果保存在arg.array中,參數sennum被忽略;
GETNCNT
返回等待semnum所代表信號燈的值增加的進程數,相當於目前有多少進程在等待semnum代表的信號燈所代表的共用資源;
GETPID
返回最後一個對semnum所代表信號燈執行semop操作的進程ID
GETVAL
返回semnum所代表信號燈的值;
GETZCNT
返回等待semnum所代表信號燈的值變成0的進程數;
SETALL
通過arg.array更新所有信號燈的值;同時,更新與本信號集相關的semid_ds結構的sem_ctime成員;
SETVAL
設置semnum所代表信號燈的值為arg.val

調用返回:調用失敗返回-1,成功返回與cmd相關:

Cmd
return value
GETNCNT
Semncnt
GETPID
Sempid
GETVAL
Semval
GETZCNT
Semzcnt

五、信號燈的限制

1、 一次系統調用semop可同時操作的信號燈數目SEMOPMsemop中的參數nsops如果超過了這個數目,將返回E2BIG錯誤。SEMOPM的大小特定與系統,redhat 8.032

2、 信號燈的最大數目:SEMVMX,當設置信號燈值超過這個限制時,會返回ERANGE錯誤。在redhat 8.0中該值為32767

3、 系統範圍內信號燈集的最大數目SEMMNI以及系統範圍內信號燈的最大數目SEMMNS。超過這兩個限制將返回ENOSPC錯誤。redhat 8.0中該值為32000

4、 每個信號燈集中的最大信號燈數目SEMMSLredhat 8.0中為250 SEMOPM以及SEMVMX是使用semop調用時應該注意的;SEMMNI以及SEMMNS是調用semget時應該注意的。SEMVMX同時也是semctl調用應該注意的。


六、競爭問題

第一個創建信號燈的進程同時也初始化信號燈,這樣,系統調用semget包含了兩個步驟:創建信號燈;初始化信號燈。由此可能導致一種競爭狀態:第一個創建信號燈的進程在初始化信號燈時,第二個進程又調用semget,並且發現信號燈已經存在,此時,第二個進程必須具有判斷是否有進程正在對信號燈進行初始化的能力。在參考文獻[1]中,給出了繞過這種競爭狀態的方法:當semget創建一個新的信號燈時,信號燈結構semid_dssem_otime成員初始化後的值為0。因此,第二個進程在成功調用semget後,可再次以IPC_STAT命令調用semctl,等待sem_otime變為非0值,此時可判斷該信號燈已經初始化完畢。下圖描述了競爭狀態產生及解決方法:


實際上,這種解決方法也是基於這樣一個假定:第一個創建信號燈的進程必須調用semop,這樣sem_otime才能變為非零值。另外,因為第一個進程可能不調用semop,或者semop操作需要很長時間,第二個進程可能無限期等待下去,或者等待很長時間。


七、信號燈應用實例

本實例有兩個目的:1、獲取各種信號燈資訊;2、利用信號燈實現共用資源的申請和釋放。並在程式中給出了詳細注釋。

#include <linux/sem.h>
#include <stdio.h>
#include <errno.h>
#define SEM_PATH "/unix/my_sem"
#define max_tries 3
int semid;
main()
{
int flag1,flag2,key,i,init_ok,tmperrno;
struct semid_ds sem_info;
struct seminfo sem_info2;
union semun arg;       //union semun: 請參考附錄2
struct sembuf askfor_res, free_res;
flag1=IPC_CREAT|IPC_EXCL|00666;
flag2=IPC_CREAT|00666;
key=ftok(SEM_PATH,'a');
//error handling for ftok here;
init_ok=0;
semid=semget(key,1,flag1);
//create a semaphore set that only includes one semphore.
if(semid<0)
{
  tmperrno=errno;
  perror("semget");
if(tmperrno==EEXIST)
//errno is undefined after a successful library call( including perror call)
//so it is saved  in tmperrno.
    {
    semid=semget(key,1,flag2);
//flag2 只包含了IPC_CREAT標誌, 參數nsems(這裡為1)必須與原來的信號燈數目一致
    arg.buf=&sem_info;
    for(i=0; i<max_tries; i++)
    {
      if(semctl(semid, 0, IPC_STAT, arg)==-1)
      {  perror("semctl error"); i=max_tries;}
      else
      {
        if(arg.buf->sem_otime!=0){ i=max_tries;  init_ok=1;}
        else   sleep(1); 
      }
    }
    if(!init_ok)
  // do some initializing, here we assume that the first process that creates the sem
  //  will finish initialize the sem and run semop in max_tries*1 seconds. else it will 
  // not run semop any more.
    {
      arg.val=1;
      if(semctl(semid,0,SETVAL,arg)==-1) perror("semctl setval error");
    }
  }
  else
  {perror("semget error, process exit");  exit();  }
}
else //semid>=0; do some initializing  
{
  arg.val=1;
  if(semctl(semid,0,SETVAL,arg)==-1)
    perror("semctl setval error");
}
//get some information about the semaphore and the limit of semaphore in redhat8.0
  arg.buf=&sem_info;
  if(semctl(semid, 0, IPC_STAT, arg)==-1)
    perror("semctl IPC STAT");   
  printf("owner's uid is %d\n",   arg.buf->sem_perm.uid);
  printf("owner's gid is %d\n",   arg.buf->sem_perm.gid);
  printf("creater's uid is %d\n",   arg.buf->sem_perm.cuid);
  printf("creater's gid is %d\n",   arg.buf->sem_perm.cgid);
  arg.__buf=&sem_info2;
  if(semctl(semid,0,IPC_INFO,arg)==-1)
    perror("semctl IPC_INFO");
  printf("the number of entries in semaphore map is %d \n",  arg.__buf->semmap);
  printf("max number of semaphore identifiers is %d \n",    arg.__buf->semmni);
  printf("mas number of semaphores in system is %d \n",   arg.__buf->semmns);
  printf("the number of undo structures system wide is %d \n",  arg.__buf->semmnu);
  printf("max number of semaphores per semid is %d \n",   arg.__buf->semmsl);
  printf("max number of ops per semop call is %d \n",  arg.__buf->semopm);
  printf("max number of undo entries per process is %d \n",  arg.__buf->semume);
  printf("the sizeof of struct sem_undo is %d \n",  arg.__buf->semusz);
  printf("the maximum semaphore value is %d \n",  arg.__buf->semvmx);
 
//now ask for available resource: 
  askfor_res.sem_num=0;
  askfor_res.sem_op=-1;
  askfor_res.sem_flg=SEM_UNDO;   
   
    if(semop(semid,&askfor_res,1)==-1)//ask for resource
      perror("semop error");
 
  sleep(3);
  //do some handling on the sharing resource here, just sleep on it 3 seconds
  printf("now free the resource\n"); 
 
//now free resource 
  free_res.sem_num=0;
  free_res.sem_op=1;
  free_res.sem_flg=SEM_UNDO;
  if(semop(semid,&free_res,1)==-1)//free the resource.
    if(errno==EIDRM)
      printf("the semaphore set was removed\n");
//you can comment out the codes below to compile a different version:     
  if(semctl(semid, 0, IPC_RMID)==-1)
    perror("semctl IPC_RMID");
  else printf("remove sem ok\n");
}



注:讀者可以嘗試一下注釋掉初始化步驟,進程在運行時會出現何種情況(進程在申請資源時會睡眠),同時可以像程式結尾給出的注釋那樣,把該程式編譯成兩個不同版本。下面是本程式的運行結果(作業系統redhat8.0):

owner's uid is 0
owner's gid is 0
creater's uid is 0
creater's gid is 0
the number of entries in semaphore map is 32000
max number of semaphore identifiers is 128
mas number of semaphores in system is 32000
the number of undo structures system wide is 32000
max number of semaphores per semid is 250
max number of ops per semop call is 32
max number of undo entries per process is 32
the sizeof of struct sem_undo is 20
the maximum semaphore value is 32767
now free the resource
remove sem ok



Summary:信號燈與其它進程間通信方式有所不同,它主要用於進程間同步。通常所說的系統V信號燈實際上是一個信號燈的集合,可用於多種共用資源的進程間同步。每個信號燈都有一個值,可以用來表示當前該信號燈代表的共用資源可用(available)數量,如果一個進程要申請共用資源,那麼就從信號燈值中減去要申請的數目,如果當前沒有足夠的可用資源,進程可以睡眠等待,也可以立即返回。當進程要申請多種共用資源時,linux可以保證操作的原子性,即要麼申請到所有的共用資源,要麼放棄所有資源,這樣能夠保證多個進程不會造成互鎖。Linux對信號燈有各種各樣的限制,程式中給出了輸出結果。另外,如果讀者想對信號燈作進一步的理解,建議閱讀sem.h原始程式碼,該文件不長,但給出了信號燈相關的重要資料結構。

附錄1 struct sem_array如下:

/*系統中的每個信號燈集對應一個sem_array 結構 */
struct sem_array {
  struct kern_ipc_perm  sem_perm;    /* permissions .. see ipc.h */
  time_t      sem_otime;      /* last semop time */
  time_t      sem_ctime;      /* last change time */
  struct sem    *sem_base;      /* ptr to first semaphore in array */
  struct sem_queue  *sem_pending;    /* pending operations to be processed */
  struct sem_queue  **sem_pending_last;   /* last pending operation */
  struct sem_undo    *undo;      /* undo requests on this array */
  unsigned long    sem_nsems;    /* no. of semaphores in array */
};



其中,sem_queue結構如下:

/* 系統中每個因為信號燈而睡眠的進程,都對應一個sem_queue結構*/
 struct sem_queue {
  struct sem_queue *  next;     /* next entry in the queue */
  struct sem_queue **  prev;
  /* previous entry in the queue, *(q->prev) == q */
  struct task_struct*  sleeper;   /* this process */
  struct sem_undo *  undo;     /* undo structure */
  int   pid;             /* process id of requesting process */
  int   status;           /* completion status of operation */
  struct sem_array *  sma;       /* semaphore array for operations */
  int  id;               /* internal sem id */
  struct sembuf *  sops;       /* array of pending operations */
  int  nsops;             /* number of operations */
  int  alter;             /* operation will alter semaphore */
};



附錄2union semun是系統調用semctl中的重要參數:

union semun {
        int val;                                      /* value for SETVAL */
        struct semid_ds *buf;          /* buffer for IPC_STAT & IPC_SET */
        unsigned short *array;         /* array for GETALL & SETALL */
        struct seminfo *__buf;         /* buffer for IPC_INFO */   //test!!
        void *__pad;
};
struct  seminfo {
        int semmap;
        int semmni;
        int semmns;
        int semmnu;
        int semmsl;
        int semopm;
        int semume;
        int semusz;
        int semvmx;
        int semaem;
};



沒有留言: