2016-04-15 27 views
0

我正在開發一個需要進程同步的項目。我遇到的問題是我使用的信號燈似乎並未在所有進程中共享。它的行爲與局部變量類似。這是一個簡化代碼,但演示了同樣的問題:C - 沒有共享所有進程的信號量

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/wait.h> 
#include <sys/types.h> 
#include <unistd.h> 
#include <time.h> 
#include <semaphore.h> 
#include <fcntl.h> 


sem_t sem_1; //Global variable (semaphore). 

int main(){ 
    sem_init(&sem_1, 1, 0);  //semaphore starts with 0   
    pid_t child_pid_or_zero = fork(); //process fork 
    if (child_pid_or_zero < 0){  
     perror("fork() error"); 
     exit (2); 
    } 

    if (child_pid_or_zero != 0){ 
     sem_wait(&sem_1);   //decrement to -1 and waits 
     printf("I am the parent %d, my child is %d.\n",getpid(),child_pid_or_zero); 

    }else{ 

     printf("i am child\n"); 
     sem_post(&sem_1);  //increments 
    } 
return 0; 
} 

父進程永遠不會獲得等待信號。我嘗試在兩個進程中添加mupltiple sem_post(),並用sem_getvalue()打印值,打印的數字似乎不被共享(每個進程增加自己的信號量)。

感謝您的幫助。

+2

「叉」後,父母和孩子有單獨的地址空間。它們是緊跟在fork之後的(或多或少)地址空間的副本,但其他任何後續更改都不會被另一個看到。 – kaylum

+1

閱讀'sem_init'手冊頁或者看到像[如何在使用共享內存的進程之間共享信號量]這樣的問題(http://stackoverflow.com/questions/8359322/how-to-share-semaphores-between-processes-using-共享內存?rq = 1) – kaylum

回答

1

POSIX對於sem_init的pshared參數(第二個參數)是如何工作還不太清楚。 Linux手冊頁解釋了它更好:

如果的pshared不爲零,則信號燈在進程間共享,並應設在共享內存

的區域分配內存,並把信號你有責任。這不是系統爲你做的事情。

+0

這不能解決發佈代碼的基本問題 – user3629249

0

信號量需要在某個共享內存中,而不是在文件全局區域中。

因此需要使用:shm_open()shm_get()mmap()有一些共享內存。

傳遞給子過程的數據被設定爲「寫入時複製」,所以當子進程調用函數:sem_post(),該數據被複制,

正如我所說的,程序需要某些共享存儲器和所述信號需要位於共享內存中。

相關問題