为了找到一个进程一次可以打开的最大信号量,我不明白为什么下面的代码_SC_SEM_NSEMS_MAX
返回-1
。
int main(void) {
long max_limit = 0;
errno = EINVAL;
max_limit = sysconf(_SC_SEM_NSEMS_MAX);
printf("max_limit : %ld error_no : %d\n",max_limit,errno);
return 0;
}
编辑:-以下是我试图手动获取的最大限制。
struct count {
sem_t sem_addr;
int count;
};
int main(void) {
int fd = 0,zero = 0;
struct count *shared;
fd = shm_open("/my_semaphore",O_RDWR|O_CREAT,0777);
if(fd == -1){
perror("shm_open");
exit(0);
}
//ftruncate(fd,4096);
write(fd,&zero,4);
shared = mmap(NULL,4096,PROT_READ|PROT_WRITE,MAP_SHARED,fd,(off_t)0);
sem_init(&shared->sem_addr,1,1);
pid_t pid = fork();
if(pid > 0) {
//printf("parent process: %d \n",getpid());
sem_wait(&shared->sem_addr);
for(int i = 0;i < 50 ;i++) {
printf("parent = %d \n",shared->count++);
}
sem_post(&shared->sem_addr);
}
else if (pid == 0) {
//printf("child process: %d \n",getpid());
sem_wait(&shared->sem_addr);
for(int i = 0;i < 50 ;i++) {
printf("child = %d \n",shared->count++);
}
sem_post(&shared->sem_addr);
}
sem_destroy(&shared->sem_addr);
return 0;
}
任何帮助都将不胜感激。
最佳答案
从手册页:
RETURN VALUE
If name is invalid, -1 is returned, and errno is set to EINVAL. Other‐
wise, the value returned is the value of the system resource and errno
is not changed. In the case of options, a positive value is returned
if a queried option is available, and -1 if it is not. In the case of
limits, -1 means that there is no definite limit.
特别注意最后一句话。所以,-1可能意味着你的系统不知道
_SC_SEM_NSEMS_MAX
或者没有限制。无论哪种方式,我解释这意味着开放信号量的最大数目不是由系统任意限制的(当然它可能受内存限制等限制)。关于c - 查找一个进程一次可以打开的最大信号量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50106374/