Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

sem_getvalue() incorrect

22 views
Skip to first unread message

Bob

unread,
Nov 6, 2009, 12:18:14 PM11/6/09
to
Im trying to demonstrate a simple semaphore
with the following code on fedora core 11:

int main()
{
#define STRERR strerror(errno)

char name[] = "semname";

int initial_count = 0;
sem_t *sem = sem_open(name, O_CREAT | O_EXCL, initial_count);
if (sem == SEM_FAILED) {
perror("sem_open");
_exit(1);
}

int count = 0;
int ret = sem_getvalue(sem, &count); // get count
if (ret < 0)
printf("sem_getvalue <%d>\n", STRERR);
printf("Start count <%d>\n", count);

sem_wait(sem); // lock
sem_getvalue(sem, &count); // get count
printf("Current count <%d>\n", count);
sem_post(sem); // unlock

if (sem_close(sem) < 0)
printf("ERROR sem_close <%d> <%d>\n", errno, STRERR);
sem_unlink(name);
}

My output isnt what I expected:
Start count <134513948>
Current count <134513947>

I expected the count to be 0 for start, then 1 after sem_wait()
Can someone tell me why its a bashed number (apparently?)
Thanks

Kenneth Brody

unread,
Nov 6, 2009, 12:42:37 PM11/6/09
to
Bob wrote:
> Im trying to demonstrate a simple semaphore
> with the following code on fedora core 11:
>
> int main()
> {
> #define STRERR strerror(errno)
>
> char name[] = "semname";
>
> int initial_count = 0;
> sem_t *sem = sem_open(name, O_CREAT | O_EXCL, initial_count);

According to my man pages, the third parameter with O_CREATE is:

The third argument to the call to sem_open() must be of type
mode_t and specifies the mode for the semaphore. Only the
S_IWUSR, S_IWGRP, and S_IWOTH bits are examined; it is not pos-
sible to grant only ``read'' permission on a semaphore. The
mode is modified according to the process's file creation mask;
see umask(2).

You then have a 4th parameter:

The fourth argument must be an unsigned int and specifies the
initial value for the semaphore, and must be no greater than
SEM_VALUE_MAX.

Since you didn't pass a 4th parameter, sem_open() will use whatever "junk"
it happens to see.

[...]


> if (ret < 0)
> printf("sem_getvalue <%d>\n", STRERR);

Here, STRERR is a char*, but you pass "%d".

[...]


> My output isnt what I expected:
> Start count <134513948>
> Current count <134513947>
>
> I expected the count to be 0 for start, then 1 after sem_wait()
> Can someone tell me why its a bashed number (apparently?)

See your man pages for sem_open() to see if it agrees with mine, that you
pass the count as the fourth parameter, not the third.

--
Kenneth Brody

Bob

unread,
Nov 6, 2009, 1:49:18 PM11/6/09
to

> See your man pages for sem_open() to see if it agrees with mine, that you
> pass the count as the fourth parameter, not the third.
>

Thanks Ken, that was the issue, I misread the man page.

0 new messages