gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:08:36 26 4
gpt4 key购买 nike

我正在尝试创建一个具有同步功能的程序,但我遇到了一个问题,即我正在创建一组大小值为 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com