To find maximum number of semaphores that one process can have open at a time, I didn't get why below code _SC_SEM_NSEMS_MAX
returns -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;
}
Edit :- Here is what I tried to get the max limit manually.
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;
}
Any help will be appreciated.
From the manual page:
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.
Note in particular the last sentence. So, -1 can either mean your system doesn't know about _SC_SEM_NSEMS_MAX
or that there is no limit. Either way, I'm interpreting that to mean that the maximum number of open semaphores is not arbitrarily restricted by the system (of course it may be limited by memory constraints, etc.).