2013-01-16 54 views
1

我有一個項目,我必須使用SYS V信號量。我有共用一個信號量(使用相同的密鑰),並使用此代碼初始化幾個過程:正確刪除幾個進程使用的SYS V信號量

bool semaphore_init(semaphore_id_t* sem, int sem_value, key_t key) 
{ 
    /* Try to get a semaphore, to check if you will be an owner */ 
    *sem = semget(key, 1, IPC_CREAT | IPC_EXCL | 0666); 
    if (*sem == -1) 
    { 
     if (errno == EEXIST) 
     { 
      /* We are not owners, get semaphore without exclusive flag */ 
      *sem = semget(key, 1, IPC_CREAT | 0666); 
      if (*sem == -1) return false; 
     } 
     else return false; 
    } 
    else 
    { 
     /* We are owners, initialize semaphore */ 
     int return_value = semctl(*sem , 0, SETVAL, sem_value); 
     if (return_value == -1) return false; 
    } 

    return true; 
} 

我的問題是:我想刪除這個信號量時使用它會終止所有進程。使用:

semctl(*sem, 0, IPC_RMID) 

不是一個選項。它立即刪除信號量,其他進程得到未定義的行爲。我只是找不到用SYS V API來做的正確方法。

回答

0

您可以使用引用計數。只要讓每個進程在信號量init之後遞增ref計數器並在進程終止時遞減它。最後一個將其減少到0也會將其刪除,或者在知道所有其他進程已終止時讓主進程清除它。

您可能還需要另一個鎖定機制來同步對引用計數器的訪問,您可能會在主進程中創建/刪除引發計數器並等待其他進程。

另外,如果您的進程可能異常終止,請留意懸掛引用。

+0

問題是圖書館是分散的。正如你所說,我將不得不使用另一個信號來進行引用計數。但誰會釋放它? –