数值结果超出范围

时间:2019-12-11 23:34:22

标签: c synchronization semaphore

我正在尝试创建一个具有同步性的程序,但是遇到一个问题,我正在创建一组大小为3的信号量。

尝试执行semctl将信号量的值设置为0时,我得到的数值结果超出范围错误。

这是它从以下位置生成错误的代码:

int main(int argc, char *argv[]){

    char *fileName = argv[0];
    int value = 0;

    int semID, memID;
    int status = 0;

    int pipe1[2], pipe2[2], pipe3[2], pipe4[2], pipe5[2], pipe6[2], pipe7[2], pipe8[2], pipe9[2];
    pid_t PID1, PID2, PID3, PID4, PID5, PID6, PID7, PID8, PID9, waitPID;
    char *buffer;
    int check = 0;

    struct sembuf operations[1];

    int argCount = 4;
    int size = 20;
    char **args = (char **) malloc( (argCount) * (sizeof (char *) ));
    args[0] =     (char *)  malloc( (size)     * (sizeof (char  ) ));
    args[1] =     (char *)  malloc( (size)     * (sizeof (char  ) ));
    args[2] =     (char *)  malloc( (size)     * (sizeof (char  ) ));
    args[3] =     (char *)  malloc( (strlen(fileName))     * (sizeof (char  ) ));

    union semun {
        int value;
        struct semid_ds *buffer;
        ushort *array;
    } arg;

    char *fileNameOutput = (char *)  "output.txt";
    FILE *fPTR = fopen(fileNameOutput, "w");

    /*
    *   Create a set of 3 semaphores to control the correct synchronization
    *   then set all semaphores to value of 0
    */

    semID = semget(key, 3, 0666 | IPC_CREAT);

    if(semID < 0){
        fprintf(stderr, "Semaphore not created\n" );
        exit(0);
    }

    printf("value of semaphore after creation: %d, %d , %d\n", semctl(semID, 0, SETVAL, arg), semctl(semID, 1, SETVAL, arg), semctl(semID, 2, SETVAL, arg) );

    if(semctl(semID, 0, SETVAL, arg) < 0){
        printf( "%s\n", strerror(errno) );
        fprintf(stderr, "was unable to set value of sempahore 0\n" );
        exit(0);
    }
    if(semctl(semID, 1, SETVAL, arg) < 0){
        fprintf(stderr, "was unable to set value of sempahore 1\n" );
        exit(0);
    }

    if(semctl(semID, 2, SETVAL, arg) < 0){
        fprintf(stderr, "was unable to set value of sempahore 2\n" );
        exit(0);
    }

1 个答案:

答案 0 :(得分:0)

arg成员尚未初始化或未分配任何值。因此,它们包含随机/垃圾值。需要这样设置:

arg.value = MY_SEM_VALUE;
int res = semctl(semID, 0, SETVAL, arg);