2011-12-17 47 views
2

我有在Linux的信號燈和叉的一個問題,這裏是我的代碼:信號+叉在linux

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/sem.h> 
#include <stdlib.h> 
#include <unistd.h> 

#define KEY 464 

void debug(int semafor_id) { 
    printf("Value of sem 0 is: %d \n", semctl (semafor_id, 0 , GETVAL , 0)); 
} 

void main() 
{ 
    int id; 
    struct sembuf operations[1]; 


    // Sreate semaphore 
    id = semget(KEY, 1, 0777 | IPC_CREAT); 


    // set value 
    operations[0].sem_num = 0; 
    operations[0].sem_op = 10; 
    operations[0].sem_flg = 0; 

    semop(id, operations, 1); 

    // show what is the value 

    debug(id); 


    // do the same with the child process 
    if(!fork()) { 
     printf("IN child process \n"); 
     debug(id); 
     exit(0); 
    } 

    semctl (id, 0 , IPC_RMID , 0); 

} 

輸出是:

  • SEM 0的值是:10
  • 兒童的過程:
  • SEM 0的值是:-1

所以SE ems我不能在子進程中使用信號量。我不認爲我需要使用共享內存。幫幫我?

回答

5

你有一個競賽條件。

如果父母在fork之後繼續執行,在孩子有機會跑之前,父母會在孩子檢查其值之前銷燬信號量。

在銷燬信號量和/或使用strerror找出孩子確切的錯誤之前,在父項中添加某種暫停或更好地使用wait