#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/types.h> //shm_open
#include <stdio.h>  //printf
#include <stdlib.h> //exit
#include <unistd.h> //close
#include <string.h> //strerror
#include <signal.h>
#include <sys/syscall.h>

/* This will be created under /dev/shm/ */
#define STATE_FILE "/program.shared"
#define  NAMESIZE 1024
#define   MAXNAMES 100

/* Define a struct we wish to share. Notice that we will allocate
 * only sizeof SHARED_VAR, so all sizes are constant
 */
struct st1
{
  char name[12];
  int heartbeat ;
  double price ;
  int iFlag ;
} ;

struct st2  {
    struct st1 ;
    char pad[64 - sizeof(struct st1)] ;
} __attribute__((aligned(64))) ;

void gexit(int) ;

int main (void)
{
int first = 0;
int shm_fd;
static struct st2  *conf;
int iret ;

  iret = sysconf(_SC_PAGESIZE) ;
  printf("pagesize=(%d)\n",iret) ;

  if((shm_fd = shm_open(STATE_FILE, (O_CREAT | O_EXCL | O_RDWR),
                       (S_IREAD | S_IWRITE))) > 0 ) {
          first = 1; /* We are the first instance */
  }
  else if((shm_fd = shm_open(STATE_FILE, (O_CREAT | O_RDWR),
                        (S_IREAD | S_IWRITE))) < 0)
  {
    printf("Could not create shm object. %s\n", strerror(errno));
    return errno;
  }
  //ftruncate(shm_fd, sizeof(SHARED_VAR));
  ftruncate(shm_fd, sizeof(struct st2)*10 );
  if((conf =  mmap(0, sizeof(struct st2) * 10 , (PROT_READ | PROT_WRITE),
                   MAP_SHARED, shm_fd, 0)) == MAP_FAILED)
  {
    return errno;

  }

  printf("(%p)\n",conf) ;

  signal(SIGINT, gexit);

  signal(SIGTERM, gexit);

  if(first) {
      /* Run a set up for the first time, fill some args */
      printf("First creation of the shm. Setting up default values\n");
      int idx,idy ;
      char strtmp[8],strfinal[48]  ;

      //for(idx=0;idx< 100;idx++)
      for(idx=0;idx< 100000000;idx++)
      {
          for(idy=0;idy<10;idy++)
          {
              while (__sync_lock_test_and_set(&((conf+idy)->iFlag), 1))
                  while ((conf+idy)->iFlag)
                      __asm volatile ("pause" ::: "memory");

              (conf+idy)->heartbeat = (conf+idy)->heartbeat + 1 ;

              __sync_lock_release(&((conf+idy)->iFlag));
          }//for idy
      }//for idx
  }//if first

  int idz ;
  for(idz=0;idz<10;idz++)
      printf("(conf+idz)->heartbeat=(%d)\n",(conf+idz)->heartbeat) ;

  close(shm_fd);
  shm_unlink(STATE_FILE);
  exit(0);
}

void gexit(int gub)
{
    shm_unlink(STATE_FILE);
    exit(0) ;
}

arrow
arrow
    全站熱搜

    hedgezzz 發表在 痞客邦 留言(0) 人氣()