0

When running this code the mutex (stored in shared memory between processes) permits the print to run twice.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <sys/wait.h>
#include <sys/mman.h>

int main(){
    int* shared = mmap(NULL, sizeof(int), PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0);
    pthread_mutex_t* mutex = mmap(NULL, sizeof(pthread_mutex_t), PROT_READ | PROT_WRITE, MAP_ANON | MAP_SHARED, -1, 0);

    int cores = 2;
    int is_son = 0;
    for (int core=0; core<cores; core++){
        if (!fork()){   // is son
            is_son++;
            printf("new son\n");
            break;
        }
    }
    if (is_son){    // only run if is son
        printf("got here\n");
        pthread_mutex_lock(mutex);
        if (!*shared){
            *shared = 1;
            printf("is in (should only print once)\n");
        }
        pthread_mutex_unlock(mutex);
        printf("left\n");
    }
    return 0;
}

Example output of wrong behaviour: Example output of wrong behaviour

Explanation of the code: We store in shared memory a boolean called shared and a mutex. Two slave processes are created. Both try to run the print function, but only one should be permitted to do so. The mutex is there so only one can enter the protected code at a time, and change shared's value to one, so that the next cant enter.

0 Answers0