信号+叉在linux

问题描述:

我有在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我不能在子进程中使用信号量。我不认为我需要使用共享内存。帮帮我?

你有一个竞赛条件。

如果父母在fork之后继续执行,在孩子有机会跑之前,父母会在孩子检查其值之前销毁信号量。

在销毁信号量和/或使用strerror找出孩子确切的错误之前,在父项中添加某种暂停或更好地使用wait