This is the mail archive of the libc-help@sourceware.org mailing list for the glibc project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Semaphores in libc


On Thu, Dec 31, 2009 at 8:57 AM, Paulo J. Matos <pocmatos@gmail.com> wrote:
> On Thu, Dec 31, 2009 at 2:50 PM, Luciano Rocha <strange@nsk.no-ip.org> wrote:
>> On Thu, Dec 31, 2009 at 02:25:07PM +0000, Paulo J. Matos wrote:
>>> Â sem_t *s = sem_open("/cvsa_driver_sem", O_CREAT, O_RDWR, 1);
>>
>> Instead of O_RDWR, you should specify the permissions for the created
>> file. Like 0600.
>>
>>> Â sem_wait(s);
>>
>> Don't forget to check if the wait was interrupted.
>>
>> With the change I mentioned, your program works fine in my computer. I
>> didn't test without the change.
>>
>
> Hi Luciano,
>
> Either I misunderstood your suggestions or the server I am running
> this in is not behaving as it should:
> #include <stdio.h>
> #include <limits.h>
> #include <stdbool.h>
> #include <fcntl.h>
> #include <sys/stat.h>
> #include <semaphore.h>
> #include <errno.h>
>
> char SEM_NAME[] = "/cvsa_driver_sem";
>
> int main(void) {
>
>
> Âsem_t *s = sem_open(SEM_NAME, O_CREAT, 0600, 1);
> Âif(s == SEM_FAILED) {
> Â Âfprintf(stderr, "Semaphore failed.\n");
> Â Âreturn 1;
> Â}
>
> Âif(sem_wait(s)) {
> Â Âif(errno == EINTR)
> Â Â Âfprintf(stderr, "Wait interrupted...");
> Â Âreturn 0;
> Â}
> Â// ------- LOCKED REGION --------------
>
> ÂFILE* fp = fopen("output", "w+");
> Âbool p = false;
>
> Âif(fp)
> Â Âfor(unsigned long i = 0; i < ULONG_MAX; ++i) {
> Â Â Âif(!p) {
> Â Â Â Âprintf("Printing...\n");
> Â Â Â Âp = true;
> Â Â Â}
> Â Â Âfprintf(fp, "hello %lu\n", i);
> Â Â}
> Âelse
> Â Âprintf("Can't open file\n");
>
> Âprintf("Closing...\n");
> Âfclose(fp);
>
> Â// ------- END LOCKED REGION -----------
> Âsem_post(s);
>
> Âsem_close(s);
> Âsem_unlink(SEM_NAME);
> Âreturn 0;
>
> }
>
>
> I compiled this file and I ran it under two Putty terminals. In both
> of them, I see "Printing..." at the same time meaning they are both in
> the critical region. :-/
> Don't you see the same thing?
>

Paulo,

I see you haven't set your line buffering mode with setvbuf.

Don't trust printf and the underlying write buffering to not mess up
the write serialization.

If you want to use printf in the critical section for your test then
call setvbuf and set it to no buffering or call fflush() within the
critical section as well to force the buffer to make the kernel write
syscall after every printf call.

Ryan S. Arnold


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]