H. Soares
H. Soares

Reputation: 203

Why are my semaphores not working as expected?

I need to print the following sentence to the console "My name is Bond, James Bond" alternating the words using semaphores.

Whenever I print the words using line breaks "\n", everything prints in the expected order, however if I don't use line breaks everything prints out of order.

This is my code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <wait.h>
#include <unistd.h>
#include <semaphore.h>
#include <string.h>

int main(){
    pid_t pid;
    int i = 0;
    sem_t *sem[4];
    char * names[4] = {"/sem_ex07_1", "/sem_ex07_2", "/sem_ex07_3", "/sem_ex07_4"};

    for(i = 0; i < 4; i++){
            sem_unlink(names[i]);
        }

    for(i = 0; i < 4; i++){
        if((sem[i] = sem_open(names[i], O_CREAT | O_EXCL, 0644, 0)) == SEM_FAILED){
            printf("sem_open() error\n");
            sem_unlink(names[i]);
            exit(1);
        }
    }

    sem_post(sem[0]);

    for(i = 0; i < 3; i++){
        pid = fork();
        if(pid == 0){
            break;
        }
    }
    if(pid == 0){
        if(i == 0){

            sem_wait(sem[0]);
            printf("My");
            sem_post(sem[1]);

            sem_wait(sem[0]);
            printf("Bond, ");
            sem_post(sem[1]);
        } else if(i == 1){

            sem_wait(sem[1]);
            printf("name ");
            sem_post(sem[2]);

            sem_wait(sem[1]);
            printf("James ");
            sem_post(sem[2]);
        } else if(i == 2){

            sem_wait(sem[2]);
            printf("is ");
            sem_post(sem[0]);

            sem_wait(sem[2]);
            printf("Bond.\n");
            sem_post(sem[3]);
        }

    } else if(pid > 0){
        sem_wait(sem[3]);

        for(i = 0; i < 4; i++){
            sem_unlink(names[i]);
        }
    }

    return 0;
}

Why is my output only correct if I add a line break on each printf?

Upvotes: 0

Views: 175

Answers (1)

reichhart
reichhart

Reputation: 889

Why is my output only correct if I add a line break on each printf?

printf() is mostly by default line buffered. stdio functions which use streams (instead of file descriptors like write() does) use a buffer.

The buffer can be set via setvbuf(3).

See also Disable buffering for stdin and stdout using setvbuf()

Upvotes: 1

Related Questions