c - 信号量 unix c 等待零

标签 c unix semaphore ipcs

我想了解如何在 unix 中等待零操作。我有这段代码,但它总是停止等待与给定相同的值。

int main(void){

    int sem;
    struct sembuf sops[2];


    if((sem = semget(IPC_PRIVATE, 1,  IPC_CREAT | 0600))==-1){
        perror("Error semget");
        return 100;
    }

    fork();
    //printf("Empieza la accion\n");

    if(semctl(sem,0,SETVAL,2)==-1){
        printf("Error semctl\n");
        exit(100);
    }
    printf("Value: %d\n",semctl(sem,0,GETVAL));
    sops[0].sem_num=0;     
    sops[0].sem_op=-1;     
    sops[0].sem_flg=0;      

    //WAIT(0)   
    sops[1].sem_num=0;     
    sops[1].sem_op=0;     
    sops[1].sem_flg=0;
    printf("Value: %d\n",semctl(sem,0,GETVAL));

    if(semop(sem,&sops,2)<0) printf("Error semop\n");
    printf("Value: %d\n",semctl(sem,0,GETVAL));
    printf("End\n");

}

最佳答案

Gcc 向我提示你的代码:

sem.c:37: warning: passing argument 2 of ‘semop’ from incompatible pointer type /usr/include/sys/sem.h:59: note: expected ‘struct sembuf *’ but argument is of type ‘struct sembuf (*)[2]’

这是它不喜欢的代码:

    if(semop(sem,&sops,2)<0) printf("Error semop\n");

如果我把它改成

    if(semop(sem,sops,2)<0) printf("Error semop\n");

然后 GCC 没有提示,程序在 semop() 调用上无限期挂起,正如我所料。

请特别注意 semop() 将所有指定的操作作为一个原子组应用,或者根本不应用。如果两个进程指定的操作重叠,那么您的程序只能继续通过 semop() 调用,这样首先执行两个递减,然后执行两个等待零。

如果我在 fork() 调用之前移动 SETVAL 操作,并且让每个进程执行两个单独的 semop,您的程序将按照您的预期运行() 调用,一个是递减信号量,然后是一个等待它变为零。

关于c - 信号量 unix c 等待零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29658201/

相关文章:

无法利用堆栈溢出

Java线程通信

linux - 如果两台机器上的文件都丢失了,如何退出 shell 脚本?

c - 生产者消费者信号量值不正确

java - 从 Java 到 C++ 的线程

c - 我需要在运行 C 程序后输入 "exit"才能获得输出

C - fgets 跳过 CR 字符

c - char[n][100]是什么意思?

python - 如何选择从终端运行哪个版本的python?

unix - 同时输出到屏幕和文件以调试程序