c - 数值结果超出范围 semctl c

标签 c synchronization semaphore

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

当尝试执行 semctl 将信号量的值设置为 0 时,我得到的数值结果超出了 strerror 范围。我不明白是什么导致了此问题。

这是生成错误的代码:

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);
    }

最佳答案

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

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

关于c - 数值结果超出范围 semctl c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59295681/

相关文章:

c++ - 'W' 打印出 W, "W"打印出 $。为什么?

C: select() - 信号中断

svn - Team Foundation Server - 使用 API 同步到 SVN

ios - 使用 STTwitterAPI 使用 twitter 登录一次

c - C 中的字符串 : pitfalls and techniques

c - 迭代结构体中的 char 指针

java - ThreadLocal 的使用如何降低可重用性

java - 如何根据用户的请求暂停和恢复多个 Java 线程?

Java 信号量中的多线程概念

c++ - 删除现有对象时出现段错误