Pazar, Haziran 28

C Posix - Shared Memory

Hi all,

i want to write about "shared memory". Okay O_o. How we can use shared memory with C Posix code ? All linux distro is supports posix library. Please check below code for "shared memory";

first code, That's code allocates memory. (warn. SHSIZE 100) sha1.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/shm.h>
#include <sys/types.h>
#include <sys/ipc.h>


#define SHSIZE 100

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


   int shmid;
   key_t key;
   char *shm;
   char *s;

   key = 9876;

   shmid = shmget(key, SHSIZE, IPC_CREAT | 0666);

          if (shmid < 0){
           perror("shmget");
            exit(1);

}

    shm = shmat(shmid, NULL, 0);

         if (shm == (char *) -1){
           perror(shm);
            exit(1);

}

   memcpy(shm, "Merhaba Dunya", 13);


   s = shm;
   s += 13;

   *s = 0;

   while(*shm != '*')
       sleep(1);

  return 0;

}

Second code, This code will use memory. sha2.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/shm.h>
#include <sys/ipc.h>
#include <sys/types.h>

#define SHSIZE 100

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


   int shmid;
   key_t key;
   char *shm;
   char *s;

   key = 9876;

   shmid = shmget(key, SHSIZE, 0666);
     if(shmid < 0){
      perror("shmget");
      exit(1);
}

   shm = shmat(shmid, NULL, 0);
    if(shm == (char *) -1) {
     perror("shmat");
     exit(1);
}

  for(s = shm; *s != 0; s++) {
     printf("%c", *s);
}

  printf ("\n");
   *shm = '*';

    return 0;


}

Memory Segment List
ipcs -m
/* This code compiled with slackware */


/*warn. before run first code./*





                                           /* Above the list have blank line our process. */






0 yorum:

Yorum Gönderme

Blogger tarafından desteklenmektedir.