linux中的信号量+ fork

Dom*_*iik 2 c 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);

}
Run Code Online (Sandbox Code Playgroud)

输出是:

  • sem 0的值是:10
  • 在儿童过程中:
  • sem 0的值是:-1

所以我似乎不能在子进程中使用信号量.我认为我不需要使用共享内存.救命?

Mat*_*Mat 5

你那里有竞争条件.

如果父级fork在子级有机会运行之后继续执行,则父级将在子级可以检查其值之前销毁该信号量.

wait在销毁信号量之前在父级中添加某种暂停或更好的使用暂停和/或用于strerror确定子级中的确切错误.