2010-08-10 31 views
0

如果我没有定义LINUX_ENV宏,一切顺利(特别是,IPC_RMID cmd返回0)。 但是如果我定义了LINUX_ENV(我正在linux系统-ubuntu10.04上运行),最后一个semctl的IPC_RMID cmd返回EINVAL,并且说无效参数,即信号量未被删除。 它似乎较早的semctl SEM_INFO cmd导致较晚的IPC_RMID cmd返回在Linux系统上的无效参数 我的代码中哪里出错?任何人都可以帮助我这个。信号量相关 - smtctl使用IPC_RMID失败,无效参数

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

//#define LINUX_ENV 

#ifdef LINUX_ENV 
#define _GNU_SOURCE 
#endif 

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

int main(int argc,char* argv[]) 
{ 
    key_t key; 
    int semid; 
    int nsems; 
    int proj_id; 

    struct semid_ds semid_ds_buf; 
    union semun semun_buf; 
    struct seminfo* sem_info; 

    proj_id=rand(); 
    key=ftok(argv[0],proj_id); 
    nsems=2; 
    semid=semget(key,nsems,IPC_CREAT|IPC_EXCL|0666); 
    if(semid==-1) 
    { 
     perror("semget failed"); 
     return -1; 

    }else 
    { 
     printf("key(%s,%d) semaphore id:%d\n",argv[0],proj_id,semid); 
    } 
    semun_buf.buf=&semid_ds_buf; 
    //nsems is ignored 
    semctl(semid,0,IPC_STAT,&semid_ds_buf); 

    printf("current number of semaphores:%lu\n",semid_ds_buf.sem_nsems); 

#ifdef LINUX_ENV 
    if(semctl(semid,0,SEM_INFO,&semun_buf)==-1) 
    { 
     printf("semctl SEM_INFO failed"); 
     return -2; 
    } 

    sem_info=(struct seminfo*)(&semid_ds_buf); 
    printf("max entries in semaphore map:%d\n",sem_info->semmap); 

#endif 
    if(semctl(semid,0,IPC_RMID,0)==-1) 
    { 
     perror("semctl IPC-RMID failed"); 
     return -3; 
    } 
    return 0; 
} 

回答

1

的SEM_INFO调用返回seminfo结构,定义如下:

struct seminfo { 
    int semmap; /* # of entries in semaphore map; 
       unused */ 
    int semmni; /* Max. # of semaphore sets */ 
    int semmns; /* Max. # of semaphores in all 
       semaphore sets */ 
    int semmnu; /* System-wide max. # of undo 
       structures; unused */ 
    int semmsl; /* Max. # of semaphores in a set */ 
    int semopm; /* Max. # of operations for semop() */ 
    int semume; /* Max. # of undo entries per 
       process; unused */ 
    int semusz; /* size of struct sem_undo */ 
    int semvmx; /* Maximum semaphore value */ 
    int semaem; /* Max. value that can be recorded for 
       semaphore adjustment (SEM_UNDO) */ 
}; 

设置返回缓冲器上述结构并再次尝试。希望能帮助到你。 (我不能使用RHEL5.4系统上,上面的代码虽然重新您的问题)


+0

谢谢,我更换**如果(了semctl(semid的,0,SEM_INFO,与semun_buf)== - 1) **。与** if(semctl(semid,0,SEM_INFO,semun_buf)== - 1)**。但为什么不semctl抱怨? – schemacs 2010-08-10 12:28:12

+0

这是因为您正在发送一个指向缓冲区的指针,该缓冲区被输入到seminfo中。 semctl()无法知道您发送的缓冲区不足以包含返回数据,因此它会继续并“损坏”堆栈,从而导致下一个semctl()调用行为不正常。 – 2010-08-11 06:02:25

+0

谢谢。这是我的错。 – schemacs 2010-08-12 14:18:54

相关问题