Listing 2: A program to load a file into shared memory


#include  <stdio.h>
#include  <string.h>
#include  <sys/stat.h>

#include  "shm_pack.h"

static  int  header_size  =  0;  

/*  load  a  binary  file  in  a  shared  memory  */

/*  Copy  the  contains  of  the  file  in  the  shared  memory  */
static  void  load_file(FILE  *fd,  SMEM  *smd)
{
    char  buffer[BUFSIZ];
    int    n_item;

    if  (header_size)
        fseek(fd,header_size,SEEK_SET);  

    while  (!feof(fd))
    {
        n_item  =  fread(buffer,1,BUFSIZ,fd);
        shm_write(buffer,1,n_item,smd);
    }
}

void  main(int  argc,  char  *argv[])
{
    int    size,  key;
    FILE  *fd;
    SMEM  *smd;
    struct  stat  statbuf;

    if  ((argc  !=  3)  &&  (argc  !=  4))
    {  fprintf(stderr,"Usage:  %s  <filename>  <key>  [-header=n]  \n",argv[0]);
        exit(-1);
    }

    fd  =  fopen(argv[1],"r");  
    if  (!fd)
    {
        fprintf(stderr,"Abort:  %s  not  found\n",argv[1]);  
        exit(-1);  
    }

    fstat(fileno(fd),&statbuf);
    size  =  statbuf.st_size;  

    key  =  atoi(argv[2]);  
    smd  =  shm_access(key,0,0);
    if  (smd  !=  NULL)
    {
        fprintf(stderr,"Abort:  key  %d  already  exists\n",key);  
        exit(-1);
    }

    if  (argc  ==  4)  
    {
        char  *header;  
        header  =  argv[3];  
        if  ((header[0]  !=  '-')  ||  (header[1]  !=  'h'))
        {  
            fprintf(stderr,"Abort:  third  option:  -header=n\n");
            exit(-1);
        }
        
        header  =  strchr(argv[3],'=');  
        if  (!header)
        {
            fprintf(stderr,"Abort:  third  option:  -header=n\n");
            exit(-1);
        }
      
        header_size  =  atoi(&header[1]);  
    }

    size  -=  header_size;
    smd  =  shm_create(key,"rw",size);  /*  create  shared  memory  */

    if  (smd  ==  NULL)
    {
        fprintf(stderr,"Abort:  cannot  create  %d\n",key);
        exit(-1);
    }

    load_file(fd,smd);  
}
/* End of File */