如何在一次操作中将信号量的值减少2

时间:2017-04-20 20:38:59

标签: synchronization semaphore

我试图理解信号量的概念,所以我想要我正在使用的程序:首先创建两个子进程然后让父进程等待,直到两个子进程完成它们的工作。这是代码:

adapGaleriaProductos

sem_wait和sem_signal:

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<time.h>
#include<string.h>
#include<limits.h>
#include<signal.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/sem.h>
#include<sys/types.h>

int main(int argc, char *argv[]) {
    int children[2], i, f;
    int sem = 0, sync = 0;

    char* cwd;
    char buff[PATH_MAX + 1];
    cwd = getcwd(buff, PATH_MAX + 1);

    key_t KEYSEM = ftok(strcat(cwd, argv[0]), 1);
    key_t KEYSEM2 = ftok(strcat(cwd, argv[0]), 2);

    srand(time(NULL));

    //create children
    for(i = 0; i < 2; i++) {
        f = fork();
        if(f != -1) {
            if(f == 0)
                break;
            else
                children[i] = f;
        }
        else
            printf("Fork Error..");
    }

    if(f > 0) {         //parent
        sem = semget(KEYSEM2, 1, 0700|IPC_CREAT);
        semctl(sem, 0, SETVAL, 0);

        sync = semget(KEYSEM, 1, 0700|IPC_CREAT);
        semctl(sync, 0, SETVAL, 0);

        // ...

        sem_wait(sem, 2);       /*** here I want to decrease the value of sem by 2 ***/

        shmdt(globalcp);

        semctl(sem, 0, IPC_RMID, 0);
        semctl(sync, 0, IPC_RMID, 0);

        exit(0);
    }
    else {
        if(i == 0) {    //first child
            sem = semget(KEYSEM2, 1, 0);
            sync = semget(KEYSEM, 1, 0);

            // ...

            sem_signal(sync, 1); // allow second child to continue

            sem_signal(sem, 1); // increase the value for the parent process to continue

            exit(0);
        }
        else {          //second child
            sem = semget(KEYSEM2, 1, 0);
            sync = semget(KEYSEM, 1, 0);

            // ...

            sem_wait(sync, 1);  // wait for child 1

            // ...

            sem_signal(sem, 1); // increase the value for the parent process to continue

            exit(0);
        }
    }
}

当我这样做时,父进程在第二个子进程之前结束。我做错了什么,我怎样才能实现目标?

提前致谢。

0 个答案:

没有答案