CS 326 Operating Systems

mmap_writer.c

DownloadView Raw

/**
 * mmap_writer.c
 *
 * This program writes a message into a shared memory object. The message is
 * enclosed in a struct. It assumes the shm object has already been set up by
 * the reading process.
 *
 * Compile (Linux): gcc -lrt -Wall -g mmap_writer.c -o writer
 * Compile (Mac): gcc -Wall -g mmap_writer.c -o writer
 * Run: ./writer shm_obj_name 'message to send'
 */

#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <sys/mman.h>
#include <unistd.h>

struct message {
    unsigned int id;
    pid_t from_pid;
    char msg[128];
};

int main(int argc, char *argv[])
{
    if (argc < 3) {
        printf("Usage: %s shm_obj_name 'message to send'\n", argv[0]);
        return 1;
    }

    char *obj = argv[1];
    char *msg_txt = argv[2];
    size_t size = sizeof(struct message);

    int shm_fd = shm_open(obj, O_RDWR);
    if (shm_fd == -1) {
        perror("shm_open");
        printf("Reminder: start the mmap reader first!\n");
        return 0;
    }

    void *block = mmap(
            NULL, /* Address (we use NULL to let the kernel decide) */
            size, /* Size of memory block to allocate */
            PROT_READ | PROT_WRITE, /* Memory protection flags */
            MAP_SHARED, /* Type of mapping */
            shm_fd, /* file descriptor */
            0 /* offset to start at within the file */);

    if (block == MAP_FAILED) {
        perror("mmap");
    }

    struct message *msg = (struct message *) block;
    msg->from_pid = getpid();
    strcpy(msg->msg, msg_txt);
    msg->id = msg->id + 1;

    return 0;
}