Shared Output: Use semaphore

We use semaphore to ensure mutual exclusion to the standard error. If the process is using standard error, the other process must wait until the semaphore is released.

Compile and run the programs with the following:

gcc process1_sol.c -pthread -o process1_sol
gcc process2_sol.c -pthread -o process2_sol
./process1_sol & ./process2_sol &
/*process1_sol.c*/
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
    sem_t *mutex;
    char *c = "This is CSCI3150--An operating system course.\n";
    // specify no buffering for stderr
    setbuf(stderr, NULL);
    mutex = sem_open("mutex_for_stderr", O_CREAT, 0666, 1);
    sem_wait(mutex);
    while (*c != '\0') {
        fputc(*c, stderr);
        c++;
        sleep(1);
    }
    sem_post(mutex);
    sem_close(mutex);
    sem_unlink("mutex_for_stderr");
    return 0;
}
/*process2_sol.c*/
#include <fcntl.h>
#include <semaphore.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
    sem_t *mutex;
    char *c = "This is CSCI3150--An operating system course.\n";
    // specify no buffering for stderr
    setbuf(stderr, NULL);
    mutex = sem_open("mutex_for_stderr", O_CREAT, 0666, 1);
    sem_wait(mutex);
    while (*c != '\0') {
        fputc(*c, stderr);
        c++;
        sleep(rand() % 2 + 1);
    }
    sem_post(mutex);
    sem_close(mutex);
    sem_unlink("mutex_for_stderr");
    return 0;
}

Last updated

Was this helpful?