semctl error: Invalid argument

#include 
#include 
#include 
#include 

key_t semid;

struct sembuf sem_down = {0, -1, 0};
struct sembuf sem_up = {0, 1, 0};
union semun {
    int val;
    struct semid_ds *buf;
    unsigned short *array;
    struct seminfo *_buf;
};


void down()
{
    semop(semid, &sem_down, 1); 
}

void up()
{
    semop(semid, &sem_up, 1);
}

int main()
{
    int ret = -1;
    union semun arg;
    arg.val = 1;
    semid = semget((key_t)22345, 1, IPC_CREAT|0666);
    if(semid == -1) {
    perror("semget error");
    return 1;
    }      

    ret = semctl(semid, 1, SETVAL, arg);
    if(ret == -1) {
    perror("semctl error");
    return 1;     
    }


    if(semid != -1) {
    down();
    printf("hello world.\n");
    sleep(10);
    up();
     }

    return 0;
}

以上代码编译可以通过,但是运行的时候,出现semctl error: Invalid argument错误。

问题出在semctl函数的第二个参数处。
有关semctl函数的使说明,man手册的说明如下:

semctl()  performs the control operation specified by cmd on the semaphore set identified by semid, or on the semnum-th semaphore of
that set.  (The semaphores in a set are numbered starting at 0.)

注意括号里边的描述,信号在信号量集中的编号是从0开始的,而我们这里的第二个参数是1,并且创建的信号量集中只有一个信号,因此会出现参数无效的错误。

修改完成之后如下:

ret = semctl(semid, 0, SETVAL, arg);

你可能感兴趣的:(Linux)