union semun{
int val;
struct senid_ds *buf;
unsigned short *array;
};
union semun arg;
int func(){
key_sem = ftok(".",67);
if(FAILURE == key_sem){
perror("\n key_sem:");
return FAILURE;
}
key_val++;
semid = semget(key_sem,1,IPC_CREAT);
if(FAILURE == semid){
perror("\n semid:");
return FAILURE;
}
printf("\n Key : %d Semaphore ID is : %d \n",key_sem,semid);
arg.val = 1;
ret = semctl(semid,0,SETVAL,arg);
}
int ret;
struct sembuf op[1];
int read_pos(){
op[0].sem_num = 0;
op[0].sem_op = -1;
op[0].sem_flg = SEM_UNDO;
printf("\n gng to lock! \n");
printf("\n semid: %d \n",details.sem_id);
ret = semop(details.sem_id,op,1);
printf("\n Locked! \n");
sleep(15);
op[0].sem_op = 1;
ret = semop(details.sem_id,op,1);
printf("\n Unlocked! \n");
return SUCCESS;
}
int main(){
read_pos();
return 0;
}
我在read(pro)中创建了2个二进制文件,其中一个没有睡眠(a.out)。
首先执行./pro 然后./a.out
虽然亲获得了Locked。 a.out也可以获得锁定。它不应该获得锁定。 我试过打印信号量ID。一样的。可能是什么原因?