gpt4 book ai didi

c - Linux系统V IPC : Unable to initialize semaphore value

转载 作者:太空狗 更新时间:2023-10-29 11:03:43 25 4
gpt4 key购买 nike

为了演示目的,我创建了一个简单的信号量初始化示例:

#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <unistd.h>
#include <stdlib.h>

int init_semaphore(int semid, int semnum, int initval)
{
union semun pack;
pack.val = initval;
return semctl(semid,semnum,SETVAL,pack);
}

但是我得到了错误:

error: aggregate ‘init_semaphore(int, int, int)::semun pack’ has incomplete type and cannot be defined

我无法理解为什么编译器会抛出错误。 header 也已正确包含。<​​/p>

最佳答案

您必须自己显式声明 union semun

根据 POSIX standard for semctl() :

The semctl() function provides a variety of semaphore control operations as specified by cmd. The fourth argument is optional and depends upon the operation requested. If required, it is of type union semun, which the application shall explicitly declare:

union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
} arg;

根据 Linux man page :

This function has three or four arguments, depending on cmd. When there are four, the fourth has the type union semun. The calling program must define this union as follows:

   union semun {
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL */
struct seminfo *__buf; /* Buffer for IPC_INFO
(Linux-specific) */
};

关于c - Linux系统V IPC : Unable to initialize semaphore value,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37577824/

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