Wednesday, April 6, 2016

Linux IPC the Shred Memory

Linux IPC Shared Memory is inter process/thread way of exchanging data.
This examples are made two programs.

shm_r.c
This source make and attach a shared memory and then check updating from other process every 1 second. When data updated "END", remove shared memory and process quit.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define DATA_SIZE 2048

int main(void) {

    int  id;
    char *shmData;
    char data[DATA_SIZE];

    // Shared memory create a new with IPC_CREATE
    if((id = shmget(IPC_PRIVATE, DATA_SIZE, IPC_CREAT|0666)) == -1){
        perror("shmget()");
        exit(-1);
    }

    printf("Shm ID = %d\n",id);

    // Shared memory attach and convert char address
    if((shmData = (char *)shmat(id, NULL, 0)) == (void *)-1){
        perror("shmat()");
    } else {
        // Write initial data to shared memory
        strcpy(shmData, "INITIALIZED DATA");
        memset(data, 0x00, DATA_SIZE);

        // Check updateing every a second.
        while( 1 ){
            // Does shared memory updated?
            if (strcmp(shmData, data) != 0) {
                printf("%s\n", shmData);
                strcpy(data, shmData);

                // Does shared memory  updated same 'END'?
                if (strcmp(data, "END") == 0) {
                    break;
                }
            }
            sleep( 1 );
        }

        // Detach shred memory
        if(shmdt( shmData )==-1){
            perror("shmdt()");
        }
    }

    // Remove shred memory
    if(shmctl(id, IPC_RMID, 0)==-1){
        perror("shmctl()");
        exit(EXIT_FAILURE);
    }

    return 0;
}



shm_r.c
This source attache created shared memory and then write a message, lastly detach one and self quit. This program needs two arguments. First, shared memory ID. Second to write message. To input shard memory ID is displayed when running shm_r.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main(int argc, char *argv[]) {

    int   id;
    char  *shmData;

    if( argc <= 2) {
        fprintf(stderr, "Usage: shm_w shm_id string\n");
        exit(EXIT_FAILURE);
    }

    // Attache shared memory
    id = atoi(argv[1]);
    if((shmData = (char *)shmat(id, 0, 0)) == (void *)-1) {
        perror("shmat()");
        exit(EXIT_FAILURE);
    } else {
        strcpy(shmData, argv[2]);
        fprintf(stderr, "Written:%s.\n", shmData);
        // Detach shared memory
        if( shmdt( shmData ) == -1) {
            perror("shmdt()");
            exit(EXIT_FAILURE);
        }
    }

    return 0;
}


No comments:

Post a Comment