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我不能在子進程中使用信號量。我不認爲我需要使用共享內存。幫幫我?