Skip to content
Snippets Groups Projects
T1.c 1.78 KiB
Newer Older
antux18's avatar
antux18 committed
#include<stdio.h>
#include<sys/mman.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<sys/wait.h>
#include<string.h>

#define SIZE 10000
#define SCRATCH_FILE "./shared-file"

void swap(int *xp, int *yp);
void sort(int arr[], int size);

int main() {
    int arr[SIZE];
    for(int i = SIZE - 1; i >= 0; i--)
        arr[(SIZE - 1) - i] = i % 2;

antux18's avatar
antux18 committed
    // Use shm_open, ftruncate, mmap, and munmap to communicate over mapped files
    int fd = open("tmp", O_CREAT|O_RDWR|O_TRUNC, 0666);
    ftruncate(fd, sizeof(int));
    float* shm = mmap(NULL, sizeof(float), PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0);

    int cpid;
    // Fork another process here
    switch (cpid = fork()) {
        case -1 :
            perror("error");
            exit(EXIT_FAILURE);
        case 0 :
            // The other process should calculate the mean
            float sum = 0;
            for (int i = 0 ; i < SIZE ; i++) {
                sum += arr[i];
            }
            float mean = sum/SIZE;
            shm[0] = mean;
            exit(0);
        default :
            // One process should calculate the median
            int status;
            if (wait(&status) == -1) {
                perror("error");
            }
            sort(arr, SIZE);
            // Print both calculated results and involved PIDs
            printf("PID: %d, median: %d\n", getpid(), arr[SIZE/2]);
            printf("PID: %d, mean: %f\n", cpid, shm[0]);
            munmap(shm, sizeof(int));
            close(fd);
    }

antux18's avatar
antux18 committed
    return 0;
}

void swap(int *xp, int *yp) {
    int temp = *xp;
    *xp = *yp;
    *yp = temp;
}

void sort(int *arr, int size) {
    for (int i = 0; i < size - 1; i++)
        for (int j = 0; j < size - i - 1; j++)
            if (arr[j] > arr[j + 1])
                swap(&arr[j], &arr[j + 1]);
}