Beispiel #1
0
static void shm(void)
{
	shm_id = create_shared_memory(SHM_KEY);
	associate_shared_memory(shm_id, &shm_addr);

	global_info_t = (info_t *) shm_addr;

	global_info_t->index_producer = 0;
	global_info_t->index_consumer = 0;
	memset(global_info_t->buffer, 0, BUFFER_SIZE);
}
Beispiel #2
0
int main(void)
{
	int count;
	int semaphore_id;
	int g_shm_id;
	int *g_shm_addr;

	pid_t pid = 1;
	pid_t pids[NO_OF_CHILDREN];

	semaphore_id = semaphore_new(SEM_KEY);
	v(semaphore_id, 1);
		
	g_shm_id = create_shared_memory(SHM_KEY);
	g_shm_addr = associate_shared_memory(g_shm_id);
	*g_shm_addr = 0;

	for (count = 0; count < NO_OF_CHILDREN; count++) {

		if (pid) {
		
			if ((pid = fork()) < 0) {
				fprintf(stderr, "The fork() function has failed: %s\n", strerror(errno));
				return EXIT_FAILURE;
			}
			
			pids[count] = pid;
			
			if (pid)
				fprintf(stderr, "#%d# Created pid process: %d\n", getpid(), (pids[count]));		
		}
		else
			break;
	}

	if (!pid)
		print_characters(semaphore_id, g_shm_addr);

	else {
		usleep(WAIT_CHILDREN);
		printf(NEW_LINE);
		
		for (count = 0; count < NO_OF_CHILDREN; count++) {
			
			kill(pids[count], SIGKILL);
			fprintf(stderr, "#%d# Killing pid process: %d\n", getpid(), pids[count]);
		
		}
		
		shared_memory_destroy(g_shm_id);
		semaphore_destroy(semaphore_id); 
	}
	exit(EXIT_SUCCESS);
}
Beispiel #3
0
int main(int argc, char *argv[])
{
    int s, ns;
    int semaphore_id;
    int shared_memory_id = 0;
    uint16_t port;
    pid_t pid;
    struct sockaddr_in client;
    char *tmp_shm_addr;
    shm_t *g_shm;

    check_args(&argc, argv, 0);

    port = (uint16_t) atoi(argv[1]);
    create_tcp_socket(&s, port);

    semaphore_id = semaphore_new(SEM_KEY);
    v(semaphore_id, 1);

    shared_memory_id = create_shared_memory(SHM_KEY);
    tmp_shm_addr = associate_shared_memory(shared_memory_id);
    g_shm = (shm_t *) tmp_shm_addr;


    while (true) {

        accept_new_connection(&s, &ns, &client);

        if ((pid = fork()) == 0)

            shandler(&ns, semaphore_id, client, g_shm);

        else {
            if (pid > 0)

                fprintf(stderr, "#%d# Father - Created child process: %d\n", getpid(), pid);

            else {
                fprintf(stderr, "The fork() function has failed: %s!\n", strerror(errno));
                shared_memory_destroy(shared_memory_id);
                semaphore_destroy(semaphore_id);
                exit(EXIT_FAILURE);
            }
        }
    }

    shared_memory_destroy(shared_memory_id);
    semaphore_destroy(semaphore_id);

    exit(EXIT_SUCCESS);
}
Beispiel #4
0
void	init_lemipc(t_lemipc *lemipc)
{
  char	*pathname;

  srand(time(NULL));
  pathname = malloc(4096 * sizeof(char));
  pathname = getcwd(pathname, 4096);
  lemipc->key = ftok(pathname, 0);
  lemipc->shmid = shmget(lemipc->key, sizeof(*lemipc->game), SHM_R | SHM_W);
  if (lemipc->shmid == -1)
    {
      printf("Shared Memory Created\n");
      create_shared_memory(lemipc);
    }
  else
    {
      printf("Already Exist\n");
      lemipc->game = (t_shared *)shmat(lemipc->shmid, NULL, 0);
    }
}
Beispiel #5
0
/**
 * Create a new bus
 * 
 * @param   file      The pathname of the bus, `NULL` to create a random one
 * @param   flags     `BUS_EXCL` (if `file` is not `NULL`) to fail if the file
 *                    already exists, otherwise if the file exists, nothing
 *                    will happen;
 *                    `BUS_INTR` to fail if interrupted
 * @param   out_file  Output parameter for the pathname of the bus
 * @return            0 on success, -1 on error
 */
int
bus_create(const char *file, int flags, char **out_file)
{
	int fd = -1, saved_errno;
	bus_t bus;
	char buf[1 + 2 * (3 * sizeof(ssize_t) + 2)];
	size_t ptr, len;
	ssize_t wrote;
	char *genfile = NULL;
	const char *env;

	if (out_file)
		*out_file = NULL;

	bus.sem_id = -1;
	bus.key_sem = -1;
	bus.key_shm = -1;
	bus.message = NULL;
	bus.first_poll = 0;

	srand((unsigned int)time(NULL) + (unsigned int)rand());

	if (file) {
		fd = open(file, O_WRONLY | O_CREAT | O_EXCL, DEFAULT_MODE);
		if (fd == -1) {
			if ((errno != EEXIST) || (flags & BUS_EXCL))
				return -1;
			goto done;
		}
	} else {
		env = getenv("XDG_RUNTIME_DIR");
		if (!env || !*env)
			env = "/run";
		genfile = malloc((strlen(env) + 6 + 7 + 30) * sizeof(char));
		if (!genfile)
			goto fail;
		if (out_file)
			*out_file = genfile;
		sprintf(genfile, "%s/bus", env);
		t(mkdirs(genfile, 0755));
		sprintf(genfile, "%s/bus/random.", env);
		len = strlen(genfile);
		genfile[len + 30] = '\0';
	retry:
		for (ptr = 0; ptr < 30; ptr++)
			genfile[len + ptr] = randomchar();
		fd = open(genfile, O_WRONLY | O_CREAT | O_EXCL, DEFAULT_MODE);
		if (fd == -1) {
			if (errno == EEXIST)
				goto retry;
			return -1;
		}
	}

	t(create_semaphores(&bus));
	t(create_shared_memory(&bus));

	sprintf(buf, "%zi\n%zi\n", (ssize_t)(bus.key_sem), (ssize_t)(bus.key_shm));
	for (len = strlen(buf), ptr = 0; ptr < len;) {
		wrote = write(fd, buf + ptr, len - ptr);
		if (wrote < 0) {
			if ((errno != EINTR) || (flags & BUS_INTR))
				goto fail;
		} else {
			ptr += (size_t)wrote;
		}
	}
	close(fd);

done:
	if (out_file && !*out_file) {
		len = strlen(file) + 1;
		*out_file = malloc(len * sizeof(char));
		memcpy(*out_file, file, len * sizeof(char));
	} else if (!out_file) {
		free(genfile);
	}
	return 0;

fail:
	saved_errno = errno;
	if (bus.key_sem)
		remove_semaphores(&bus);
	if (bus.key_shm)
		remove_shared_memory(&bus);
	if (fd == -1)
		close(fd);
	if (out_file)
		*out_file = NULL;
	free(genfile);
	unlink(file);
	errno = saved_errno;
	return -1;
}
Beispiel #6
0
int main(int argc, char **argv)
{
/**************************************************************/
/**************************  FROM previous version
  CVBoardTypes VMEBoard;
  short Device=0;
  short Link=0;
  int32_t BHandle;

  VMEBoard=cvV1718;
  Device=0;
  if (CAENVME_Init( VMEBoard, Link, Device, &BHandle) != cvSuccess){
    printf("error opening the device\n%s",""); 
    //exit(1);
  }
**************************************************/
//  if (argc<=1){printf("%s\n"," ...  consider \" ./gregory -r /tmp/lockfile\" for gregory.net");}


///////////////////////////////////// lockfile from argument (.net)
  char lockfile[180]="";
  Targs args;



  parse_arguments(argc,argv, &args);//in main=normal var, outsourced with 
  if (args.rvalue!=NULL){strncpy( lockfile ,  args.rvalue,  180 );}
  printf( "lockfile is ...  %s\n", lockfile  );

  // ENVIRONMENT-------------
  //  char* BinPath, *DataPath;
  BinPath = getenv ("GREGORY");
  if (BinPath==NULL){
    BinPath=new char[2]; strcpy(BinPath, "./");
  }
  DataPath = getenv ("GREGORY_DATA");
  if (DataPath==NULL){
    DataPath=new char[2]; strcpy(DataPath, "./");
  }

  //  printf("%s\n","   export GREGORY=");
  //  printf("%s\n","   export GREGORY_DATA=");
  //  printf("%s\n","");
  printf("%s\n","");
  printf( "binary path: %s  (not used yet...)\n",BinPath );
  printf( "data   path: %s\n",DataPath );

  for (int ch=0;ch<8;ch++){
  WaveBinfh[ch]=NULL;
  }

  // FILL THE TABLE OF FUNCTIONS ===========================TABLE
  int ic=0;
  sprintf( compile_table[ic].name, "%s", "get_status" );
      compile_table[ic].addr=(functiontype_i)&vme_get_stat_reg;
      ic++;
  sprintf( compile_table[ic].name, "%s", "get_version" );
      compile_table[ic].addr=(functiontype_i)&vme_get_version;
      ic++;

      /*
  sprintf( compile_table[ic].name, "%s", "v1718_control" );
      compile_table[ic].addr=(functiontype_i)&v1718_control;
      ic++;
      */

      //-----------------------------------------------------

  //  printf("\nlist of known functions\n%s" , "");
  //  for (icc=0;icc<ic;icc++){
//      printf( "  %s\n", compile_table[icc].name  );
//  }
  printf("%50c\n",'-');
  // END OF TABLE ==========================================TABLE



  mmap_file=create_shared_memory( 1, "vme" );
  mmap_file2=create_shared_memory( 1, "vmeOUT" );
  
  mmap_fileS=create_shared_memory( 2, "socket" );
  mmap_fileO=create_shared_memory( 3, "oscilo" );

  mmap_fileC=create_shared_memory( 4, "counter" );
  /*
  //====================================== MMAP ====== communication 
  system("dd if=/dev/zero of=mmap.in  bs=4096  count=1 2> /dev/null");
  if ((mmapfd = open("mmap.in", O_RDWR, 0)) == -1) err(1, "open");
  mmap_file=(char*)mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, mmapfd, 0);
  if (mmap_file == MAP_FAILED) errx(1, "either mmap");
  strcpy(mmap_file,  "... this is an initial input.\0\0\0"  ); // "acq_setup.xml\nrun=1\n";
  //====================================== MMAP ====== communication


  //====================================== MMAP ====== communication 
  system("dd if=/dev/zero of=mmap.out  bs=4096  count=1 2> /dev/null");
  if ((mmapfd2 = open("mmap.out", O_RDWR, 0)) == -1) err(1, "open");
  mmap_file2=(char*)mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, mmapfd2, 0);
  if (mmap_file2 == MAP_FAILED) errx(1, "either mmap2");
  strcpy(mmap_file2,  "... no output at the moment...\0\0\0"  ); // "acq_setup.xml\nrun=1\n";
  //====================================== MMAP ====== communication



  //====================================== MMAP ====== communication server sock
  system("dd if=/dev/zero of=mmap.socket  bs=4096  count=1 2> /dev/null");
  if ((mmapfdS = open("mmap.socket", O_RDWR, 0)) == -1) err(1, "open");
  mmap_fileS=(char*)mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, mmapfdS, 0);
  if (mmap_fileS == MAP_FAILED) errx(1, "either mmapS");
  strcpy(mmap_fileS,  "...................o=ok;X=error...\0\0\0"  ); // "acq_setup.xml\nrun=1\n";
  //====================================== MMAP ====== communication


  //====================================== MMAP ====== communication server OSCILO
  system("dd if=/dev/zero of=mmap.oscilo  bs=4096  count=1 2> /dev/null");
  if ((mmapfdO = open("mmap.oscilo", O_RDWR, 0)) == -1) err(1, "open");
  mmap_fileO=(char*)mmap(NULL, 4096, PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, mmapfdO, 0);
  if (mmap_fileO == MAP_FAILED) errx(1, "either mmapS");
  strcpy(mmap_fileO,  ".......no command to Oscilo...\0\0\0"  ); // "acq_setup.xml\nrun=1\n";
  //====================================== MMAP ====== communication

  */





  /*
  //====================================== MMAP ====== communication  4MB
  char cmd3[100];
  char fname3[100];
  sprintf( cmd3,"dd if=/dev/zero of=%s/mmap.histo  bs=4096  count=1024 2> /dev/null",
	   DataPath );
  sprintf( fname3, "%s/mmap.histo",  DataPath );
  system( cmd3);
  if ((mmapfd3 = open( fname3, O_RDWR, 0)) == -1) err(1, "open");
  mmap_file3=(char*)mmap(NULL, 4194304 , PROT_READ|PROT_WRITE, MAP_FILE|MAP_SHARED, mmapfd3, 0);
  if (mmap_file3 == MAP_FAILED) errx(1, "either mmap3");
  */
  //  strcpy(mmap_file3,  "... no output at the moment...\0\0\0"  ); // "acq_setup.xml\nrun=1\n";
  //====================================== MMAP ====== communication

  //===========histogram array 
  //http://root.cern.ch/root/roottalk/roottalk01/3614.html
  //hclus[9] = new TH1F("name","descr",100,0,1000);  hclus[9]->Fill(1);
  //- BIG TRICK with allocation. We pray 4MB isok
  // OBJECTS have to do  TMapFile ... virtual classes etc.
  //TH1F **harray;
  // harray=new(mmap_file3) TH1F*[8];

//http://root.cern.ch/root/html/TMapFile.html#TMapFile:Add
//http://root.cern.ch/root/roottalk/roottalk98/2340.html
//http://root.cern.ch/root/roottalk/roottalk04/0352.html
//http://root.cern.ch/root/roottalk/roottalk04/0341.html


  //  initialize  threads................................ALLOCATE
  tinfo = (thread_info *)calloc(NTHREADS , sizeof(thread_info) );
  if (tinfo == NULL) {printf("calloc failed%s\n", "");return 1;}
  for (int tnum = 0; tnum < NTHREADS; tnum++) {tinfo[tnum].thread_num=-1;}


   //==========================================CORE

 int cmd_param[100];   //set of parameters// minimum 10!
 int i=0; // CMD counter
 int res;
 printf("\n.h     for help\n\n%s", "");

 //---------------------infinite loop ----------------------------
     char prefix[20]="      ";
     char posfix[20]="...";

   



     
  while(1==1){
   i++; 
   usleep(100*1000);  // 50ms is enough to finish thread..
   cmd_line( i );                   // shows PROMPT; reads INPUT to cmd_buffer;
   res=get_cmd_name(    cmd_param );//  1=quit; 2=list
   if (res != 0 ){ 


     //   .n newrun?   .r runnumber!    .ls !
     //   .s status   .l  LOAD!   .s save  .c comment .f file  .n numberrun ??
     //  filename send  with 'start (maybe run and file commands before)'


     if ( strcmp(cmd_buffer,".q")==0 ){  //.q
       printf("%s quitting %s\n",  prefix, posfix );
       global_flag_quit=-1;        // only LOOP itself

       strcpy(mmap_file,"quit\0"); // send it to gregory.mmap
       strcpy(mmap_fileO,"quit\0"); // send it oscilo
       //       strcpy(mmap_fileS,"quit\0"); // send it oscilo
       strcpy(mmap_fileC,"quit\0"); // send it oscilo
       
       // i will need to shutdown the socket
       int socket_fd=atoi(mmap_fileS); // get (slowly) handle
       shutdown( socket_fd, 2 );
       break;  // BREAK FROM WHILE 1==1 .... quit
     }                // .q


     
     if ( strcmp(cmd_buffer,".s")==0 ){  //.s
       if ( mmap_fileS[16] == 'o' ){
       int socket_fd=atoi(mmap_fileS); // bad trick -get handle
       printf("%s socket %d port %s  %s\n", prefix,socket_fd,PORT,posfix);
       //       sprintf(outline,"%d %d %d\n%c", 1, 2 ,3 , '\0');
       int socker[3]; // 32 bit ZH data for socket  e0000001 e0010123 0xf0000000
       socker[0]=0xe0010000;
       socker[1]=0x000100ff;
       //       socker[2]=0x0001; //channel
       //       socker[3]=0x00ff; //value 
       socker[2]=0xf0000000;
       //       socker[5]=0x0000;
       //       int tmp=send(socket_fd, outline, strlen(outline), 0 );
       int tmp=send(socket_fd, socker, sizeof(socker), 0 );
       if (tmp < 0){
	 printf(" !...socket error ... i block  mmap.socket from now\n");
	 mmap_fileS[16] = 'X';
	 //shutdown( socket_fd, 2 );
       }
       }else{ // socked_fd blocked  [16]==X  not "o"
	 printf(" !...socket  blocked due to ealier error%s\n","");
       }
     }               // .s


     
     
     //--- exact match strcmp
     //--- strstr means line start match
     if ( strstr(cmd_buffer,".r")==cmd_buffer ){  // .r   RUN number
       char oldr[70];
       int newri=1; 
       char cmdls[200];
       sprintf( cmdls,"ls -1tr %s | grep run | grep \\.dat |tail -1 | awk -F _ '{sub(\"run\",\"\");print $1}' > RUNNUM ",   DataPath );
       system(cmdls);

       sprintf( cmdls,"ls -ltrh %s/run*.dat 2>/dev/null | tail -1 | awk '{print $9,\" \",$5}' > RUNNAMELAST ",   DataPath );
       system(cmdls);

       sprintf( cmdls,"ls -tr1 %s| grep -ie '^run[0-9]' | sed 's/run0*//' | cut -d. -f 1 | cut -d _ -f 1 | sort -n | tail -1 > RUNNEXT ",   DataPath );
       system(cmdls);

       //=============  read  ll -h output with size ==========
       FILE *frn=fopen("RUNNAMELAST","r");
       if (frn!=NULL){
	 memset(&oldr[0], 0, sizeof(oldr));
	 fread( oldr, 1, sizeof(oldr), frn );
	 oldr[ strlen(oldr)-1 ]='\0';
	 fclose(frn);
	 printf("%s ... LAST SAVED ON DISK\n", oldr );
       }
       //----------------------------------
       frn=fopen("RUNNUM","r");
       if (frn!=NULL){
	 fread( oldr, 1, sizeof(oldr), frn );
	 fclose(frn);
	 if ( strlen(oldr)>0){
	   sscanf(oldr,"%d", &newri );   //from   oldr => newri
	   printf("CURR /on disk/  RUN =%5d\n", newri );
	   //printf("NEXT  proposed  RUN =%5d\n", newri+1 );
	 }
       }//no RUNNUM file
       //-----------------------------
       frn=fopen("RUNNEXT","r");
       if (frn!=NULL){
	 fread( oldr, 1, sizeof(oldr), frn );
	 fclose(frn);
	 if ( strlen(oldr)>0){
	   sscanf(oldr,"%d", &newri );   //from   oldr => newri
	   //   printf("CURR /on disk/  RUN =%5d\n", newri );
	   printf("NEXT  proposed  RUN =%5d\n", newri+1 );
	 }else{ newri=1;}
       }//no RUNNUM file
       //-----------------------------
       printf("%s to change the run number use run x   %s\n",prefix,posfix);
       printf("%s run 0 ... means no data file   %s\n",prefix,posfix);
       sprintf(cmdls,"run %d",  newri+1 );
       //       strcpy( mmap_file, "run              " );
       strcpy( mmap_file,  cmdls   );
       printf("%s run  %d  ... command was sent%s\n",prefix,newri+1, posfix);
     } //  .r                   RUN NUMBER 


     //means - '.ls' on the line start 
     if ( strstr(cmd_buffer,".ls")==cmd_buffer ){  // .ls
       //       printf("%s listing %s\n",  prefix, posfix );
       for (int tnum = 0; tnum < NTHREADS; tnum++) {

	 if ( (tnum==0) && (tinfo[tnum].thread_num==1) ){
	   printf("[--M--]          process %d (of %d): measurement thread ACTIVE\n", tnum+1, NTHREADS);}
	 else if(tnum==0) {
	   printf("[--M--]          process %d (of %d): measurement thread NOT LOADED\n", tnum+1, NTHREADS);}

	 if ( (tnum==1) && (tinfo[tnum].thread_num==2 )){
	   printf("[--M--]          process %d (of %d): socket      thread ACTIVE\n", tnum+1, NTHREADS);}
	 else if(tnum==1) {
	   printf("[--M--]          process %d (of %d): socket      thread NOT LOADED\n", tnum+1, NTHREADS);}

	 if ( (tnum==2) && (tinfo[tnum].thread_num==3 )){
	   printf("[--M--]          process %d (of %d): oscilo      thread ACTIVE\n", tnum+1, NTHREADS);}
	 else if(tnum==2) {
	   printf("[--M--]          process %d (of %d): oscilo      thread NOT LOADED\n", tnum+1, NTHREADS);}

	 if ( (tnum==3) && (tinfo[tnum].thread_num==4 )){
	   printf("[--M--]          process %d (of %d): Countr      thread ACTIVE\n", tnum+1, NTHREADS);}
	 else if(tnum==3) {
	   printf("[--M--]          process %d (of %d): Countr      thread NOT LOADED\n", tnum+1, NTHREADS);}

	 /*
	 if (tinfo[tnum].thread_num>0){
	   printf("         process %d (of %d): ACTIVE\n", tnum+1, NTHREADS);
	   //	   printf("         file size %d MB\n", 0 );
	 }else{
	   if (tinfo[tnum].thread_num==1){
	     printf("         process %d (of %d): measurement thread NOT LOADED\n", tnum+1, NTHREADS);}
	   else if (tinfo[tnum].thread_num==2){
	     printf("         process %d (of %d): socket      thread NOT LOADED\n", tnum+1, NTHREADS);}
	   else {printf("         process %d (of %d): socket      thread NOT LOADED\n", tnum+1, NTHREADS);}
	 }
	 */
       }// NTHREADS

       printf("[--M--] last message:\n %s\n", mmap_file2 );
       char text[100]; time_t now = time(NULL);
       struct tm *t = localtime(&now);
       strftime(text, sizeof(text)-1, "%Y/%m/%d_%H:%M:%S ", t);
       printf("%s ...\n", text);
       fflush(stdin);
       global_flag_list=1; 

       /*       //======= THIS IS A WAY TO PRINT ON PORT 7777 =======
       int socket_fd=atoi(mmap_fileS);
       if (socket_fd != -1) {
       	 if (send(socket_fd,  "\nAHOJ\n"   , 6, 0) == -1) perror("ls");
	 } 
       */

     }                // .ls     list.............
     
     
     
     if ( strcmp(cmd_buffer,".l")==0 ){  // .l   LOAD
       //       printf("%s LOADing %s\n",  prefix, posfix );
       int tnum, pth_res;
       for (tnum = 0; tnum < NTHREADS; tnum++) {
	 if (tinfo[tnum].thread_num<0){ 
	   tinfo[tnum].thread_num = tnum + 1;
	   //	   if (tnum==0){
	   pth_res = pthread_create(&tinfo[tnum].thread_id, NULL,
				    &loop_thread,  &tinfo[tnum] );
	   //	   }
	   //	   if (tnum==1){
	   //	   pth_res = pthread_create(&tinfo[tnum].thread_id, NULL,
	   //				    &loop_thread2,  &tinfo[tnum] );
	   //	   }
	   if ( pth_res != 0){printf("pthread_create failed%s\n","");return 1;}
	 }// _num<0 == not active thread=> you can reload
	 else{
	   printf("%s thread %d is already active== %d %s no action\n",  prefix,tnum, tinfo[tnum].thread_num, posfix );
	   //	   printf(" thread %d is already active== %d (no action)\n", tnum, tinfo[tnum].thread_num);
	 }// else already active
       }//for all threads
     }                // ..  LOAD
     

     /* if ( strcmp(cmd_buffer,".s")==0 ){  // .s   LOAD SERVER */
     /*   printf("%s loading network Server %s\n",  prefix, posfix ); */
     /*   int tnum, pth_res; */
     /*   for (tnum = 0; tnum < NTHREADS; tnum++) { */
     /* 	 if (tinfo[tnum].thread_num<0){  */
     /* 	   tinfo[tnum].thread_num = tnum + 1; */
     /* 	   pth_res = pthread_create(&tinfo[tnum].thread_id, NULL, */
     /* 				    &loop_thread,  &tinfo[tnum] ); */
     /* 	   if ( pth_res != 0){printf("pthread_create failed%s\n","");return 1;} */
     /* 	 }// _num<0 == not active thread=> you can reload */
     /* 	 else{ */
     /* 	   printf("%s thread %d is already active== %d %s no action\n",  prefix,tnum, tinfo[tnum].thread_num, posfix ); */
     /* 	   //	   printf(" thread %d is already active== %d (no action)\n", tnum, tinfo[tnum].thread_num); */
     /* 	 }// else already active */
     /*   }//for all threads */
     /* }                // ..  LOAD SERVER */
     


  
     if ( strcmp(cmd_buffer,".h")==0 ){  // .h
       //       printf("%s help %s\n",  prefix, posfix );
       printf("%s .h   %s help\n", prefix, posfix  );
       printf("%s .l   %s LOAD  ALL THREADS\n", prefix, posfix  );
       printf("%s .s   %s TEST  network server on port %s\n", prefix, posfix , PORT );
       printf("%s .r   %s look at run number\n", prefix, posfix  );
       printf("%s .ls  %s list\n", prefix, posfix  );
       printf("%s .q  %s QUIT\n", prefix, posfix  );
       printf("%s ------ %s measurement thread commands ------:\n" , prefix, posfix  );
       printf("%s qu   %s quit       \n"  , prefix, posfix);
       printf("%s sta  %s start      \n" , prefix, posfix );
       printf("%s te   %s test = start +no save\n" , prefix, posfix );
       printf("%s sto  %s STOP       \n" , prefix, posfix );
       printf("%s sts  %s status     \n" , prefix, posfix );
       printf("%s cl   %s clear histo     \n" , prefix, posfix );
       printf("%s hi   %s histogram (save histogram to txt) \n" , prefix, posfix );
       printf("%s wa   %s waveform  (save waveform to txt,mmap)  \n" , prefix, posfix ); //not used anymore
       printf("%s tr   %s trigger    \n" , prefix, posfix );
       printf("%s in   %s init       \n" , prefix, posfix );
       //       printf("%s aon  %s autosaveON \n" , prefix, posfix );
       //       printf("%s aof  %s autosaveOFF\n" , prefix, posfix );

       printf("%s won  %s wavesaveON\n" , prefix, posfix );
       printf("%s wof  %s wavesaveOFF\n" , prefix, posfix );
       printf("%s pd   %s probe_down \n" , prefix, posfix );
       printf("%s pu   %s probe_up   \n" , prefix, posfix );
       printf("%s re   %s restart    \n" , prefix, posfix );
       printf("%s don  %s displayON  \n" , prefix, posfix );
       printf("%s dof  %s displayOFF \n" , prefix, posfix );
       
     } // .h ==============================================================HELP


   } // was an internal command==============================
   else{
     if (DEBUGGREG>0)
     printf("                                      cmd_name=%s\n", cmd_name);

     //     strcpy( mmap_file,  cmd_buffer ); //command directly to mmap_file........
     //translate to better phrases .....................

     if (strstr(cmd_buffer,"qu")!=NULL)  strcpy( mmap_file, "quit" );
     if (strstr(cmd_buffer,"qu")!=NULL)  strcpy( mmap_fileO, "quit" );
     //     if (strstr(cmd_buffer,"qu")!=NULL)  strcpy( mmap_fileS, "quit" );
     if (strstr(cmd_buffer,"qu")!=NULL)  strcpy( mmap_fileC, "quit" );

     if (strstr(cmd_buffer,"run")!=NULL) strcpy( mmap_file,  cmd_buffer ); // send the number
     
     if (strstr(cmd_buffer,"sta")!=NULL) strcpy( mmap_file, "start" );
     if (strstr(cmd_buffer,"sta")!=NULL) strcpy( mmap_fileO, "start" ); //Oscilo
     if (strstr(cmd_buffer,"sta")!=NULL) strcpy( mmap_fileC, "start" ); //Oscilo

     if (strstr(cmd_buffer,"te")!=NULL)  strcpy( mmap_file, "test" ); //must do wa
     if (strstr(cmd_buffer,"te")!=NULL)  strcpy( mmap_fileO, "test" ); //Oscilo
     if (strstr(cmd_buffer,"te")!=NULL)  strcpy( mmap_fileC, "test" ); //Oscilo

     if (strstr(cmd_buffer,"go")!=NULL)  printf(".. not programmed yet\n%s","");
     if (strstr(cmd_buffer,"go")!=NULL)  strcpy( mmap_fileO, "go" ); //Oscilo
     if (strstr(cmd_buffer,"go")!=NULL)  strcpy( mmap_fileC, "go" ); //Oscilo

     if (strstr(cmd_buffer,"sto")!=NULL) strcpy( mmap_file, "STOP" );
     if (strstr(cmd_buffer,"sto")!=NULL) strcpy( mmap_fileO, "stop" ); //Oscilo 
     if (strstr(cmd_buffer,"sto")!=NULL) strcpy( mmap_fileC, "stop" ); //Oscilo 

     if (strstr(cmd_buffer,"stat")!=NULL)strcpy( mmap_file, "status" );
     if (strstr(cmd_buffer,"sts")!=NULL) strcpy( mmap_file, "status" );

     if (strstr(cmd_buffer,"cl")!=NULL)  strcpy( mmap_file, "clear" );
     if (strstr(cmd_buffer,"hi")!=NULL)  strcpy( mmap_file, "histogram" );
     // not used anymore
     if (strstr(cmd_buffer,"wa")!=NULL)  strcpy( mmap_file, "waveform" ); // ? is it?
     if (strstr(cmd_buffer,"tr")!=NULL)  strcpy( mmap_file, "trigger" );
     if (strstr(cmd_buffer,"in")!=NULL)  strcpy( mmap_file, "init" );
     //notused anymore ... autosave==1
     if (strstr(cmd_buffer,"aon")!=NULL) strcpy( mmap_file, "autosaveON" );
     if (strstr(cmd_buffer,"aof")!=NULL) strcpy( mmap_file, "autosaveOFF" );
     //NOW autosave==111 ! wav file
     if (strstr(cmd_buffer,"won")!=NULL) strcpy( mmap_file, "wavesaveON" );
     if (strstr(cmd_buffer,"wof")!=NULL) strcpy( mmap_file, "wavesaveOFF" );

     if (strstr(cmd_buffer,"pd")!=NULL)  strcpy( mmap_file, "probe_down" );
     if (strstr(cmd_buffer,"pu")!=NULL)  strcpy( mmap_file, "probe_up" );
     if (strstr(cmd_buffer,"re")!=NULL)  strcpy( mmap_file, "restart" );
     if (strstr(cmd_buffer,"don")!=NULL) strcpy( mmap_file, "displayON" );
     if (strstr(cmd_buffer,"dof")!=NULL) strcpy( mmap_file, "displayOFF" );     

     if (strstr(cmd_buffer,"ac")!=NULL) strcpy( mmap_fileO, "accumulateXMGR" );     

//     if (strstr(cmd_buffer,"")!=NULL) strcpy( mmap_file, "" );
     //     if (strstr(cmd_buffer,"")!=NULL) strcpy( mmap_file, "" );
     // NO this would spam the output	printf("%s\n", mmap_file2 );
	fflush(stdin);
     

     /* for (icc=0;icc<ic;icc++){ */
     /*   if ( strcmp(cmd_name,compile_table[icc].name)==0){ */
     /* 	 if (DEBUGGREG>0) */
     /*  	 printf("                                      matches =%d\n", icc); */
     /* 	 compile_table[icc].addr( cmd_param[0] ); */
     /*   }//match */
     /* } //for icc=0--- */
     /* //PERFORM ON YOUR OWN */

   }// else =====   real command
  }// INF.WHILE.
   //==========================================CORE




  
  // NOW  QUITTING ROUTINES ===========================


 global_flag_quit=-1; // SEND SIGNAL TO THREAD
 printf("[##M##]       ........master is waiting for threads\n");fflush(stdin);

 // printf("%s\n","------------------------------Thread-close-begin");fflush(stdin);
 for (int tnum = 0; tnum < NTHREADS; tnum++) {
   printf("[##M##]... waiting thread %d finish ...\n", tnum+1);fflush(stdin);
   int pth_res = pthread_join(tinfo[tnum].thread_id, NULL );
   if (pth_res != 0){printf("pthread_join failed%s'\n","");
     //exit(1); // if no thread => quit to socat doesnot work
   }
   printf("[##M##] master join : thread %d (of %d) arrived\n",
	  tnum+1, NTHREADS);
   //	  tinfo[tnum].thread_num, NTHREADS);
   fflush(stdin);
   //	       printf("thread %d/%d\n", tnum+1, NTHREADS);fflush(stdin);
 }
 if (tinfo!=NULL){ free(tinfo);}
 printf("%s\n","------------------------------Thread-close-end");fflush(stdin);

 




 // REMOVE LOCKFILE IS EXISTT ********************************
 //   this is important to let the  script know "gregory has ended"
 //   ................................socat has a problem with kill
 if ( filexists(lockfile)==1  ) {
   printf("File %s exist\n", lockfile );fflush(stdin);
   if( remove( lockfile ) != 0 ){
     perror( "Error deleting file" );
   }else{
     puts( "File successfully deleted" );
   }
 }
 
 exit(0);
}//===================================================================MAIN
Beispiel #7
0
/*
 * Prepare physical memory mapping: fill configuration structure with
 * these infos, return 0 on success.
 *  1. map N huge pages in separate files in hugetlbfs
 *  2. find associated physical addr
 *  3. find associated NUMA socket ID
 *  4. sort all huge pages by physical address
 *  5. remap these N huge pages in the correct order
 *  6. unmap the first mapping
 *  7. fill memsegs in configuration with contiguous zones
 */
static int
rte_eal_hugepage_init(void)
{
	struct rte_mem_config *mcfg;
	struct hugepage *hugepage, *tmp_hp = NULL;
	struct hugepage_info used_hp[MAX_HUGEPAGE_SIZES];

	uint64_t memory[RTE_MAX_NUMA_NODES];

	unsigned hp_offset;
	int i, j, new_memseg;
	int nrpages, total_pages = 0;
	void *addr;

	memset(used_hp, 0, sizeof(used_hp));

	/* get pointer to global configuration */
	mcfg = rte_eal_get_configuration()->mem_config;

	/* for debug purposes, hugetlbfs can be disabled */
	if (internal_config.no_hugetlbfs) {
		addr = malloc(internal_config.memory);
		mcfg->memseg[0].phys_addr = (phys_addr_t)(uintptr_t)addr;
		mcfg->memseg[0].addr = addr;
		mcfg->memseg[0].len = internal_config.memory;
		mcfg->memseg[0].socket_id = 0;
		return 0;
	}


	/* calculate total number of hugepages available. at this point we haven't
	 * yet started sorting them so they all are on socket 0 */
	for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
		/* meanwhile, also initialize used_hp hugepage sizes in used_hp */
		used_hp[i].hugepage_sz = internal_config.hugepage_info[i].hugepage_sz;

		total_pages += internal_config.hugepage_info[i].num_pages[0];
	}

	/*
	 * allocate a memory area for hugepage table.
	 * this isn't shared memory yet. due to the fact that we need some
	 * processing done on these pages, shared memory will be created
	 * at a later stage.
	 */
	tmp_hp = malloc(total_pages * sizeof(struct hugepage));
	if (tmp_hp == NULL)
		goto fail;

	memset(tmp_hp, 0, total_pages * sizeof(struct hugepage));

	hp_offset = 0; /* where we start the current page size entries */

	/* map all hugepages and sort them */
	for (i = 0; i < (int)internal_config.num_hugepage_sizes; i ++){
		struct hugepage_info *hpi;

		/*
		 * we don't yet mark hugepages as used at this stage, so
		 * we just map all hugepages available to the system
		 * all hugepages are still located on socket 0
		 */
		hpi = &internal_config.hugepage_info[i];

		if (hpi->num_pages == 0)
			continue;

		/* map all hugepages available */
		if (map_all_hugepages(&tmp_hp[hp_offset], hpi, 1) < 0){
			RTE_LOG(DEBUG, EAL, "Failed to mmap %u MB hugepages\n",
					(unsigned)(hpi->hugepage_sz / 0x100000));
			goto fail;
		}

		/* find physical addresses and sockets for each hugepage */
		if (find_physaddr(&tmp_hp[hp_offset], hpi) < 0){
			RTE_LOG(DEBUG, EAL, "Failed to find phys addr for %u MB pages\n",
					(unsigned)(hpi->hugepage_sz / 0x100000));
			goto fail;
		}

		if (find_numasocket(&tmp_hp[hp_offset], hpi) < 0){
			RTE_LOG(DEBUG, EAL, "Failed to find NUMA socket for %u MB pages\n",
					(unsigned)(hpi->hugepage_sz / 0x100000));
			goto fail;
		}

		if (sort_by_physaddr(&tmp_hp[hp_offset], hpi) < 0)
			goto fail;

		/* remap all hugepages */
		if (map_all_hugepages(&tmp_hp[hp_offset], hpi, 0) < 0){
			RTE_LOG(DEBUG, EAL, "Failed to remap %u MB pages\n",
					(unsigned)(hpi->hugepage_sz / 0x100000));
			goto fail;
		}

		/* unmap original mappings */
		if (unmap_all_hugepages_orig(&tmp_hp[hp_offset], hpi) < 0)
			goto fail;

		/* we have processed a num of hugepages of this size, so inc offset */
		hp_offset += hpi->num_pages[0];
	}

	/* clean out the numbers of pages */
	for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++)
		for (j = 0; j < RTE_MAX_NUMA_NODES; j++)
			internal_config.hugepage_info[i].num_pages[j] = 0;

	/* get hugepages for each socket */
	for (i = 0; i < total_pages; i++) {
		int socket = tmp_hp[i].socket_id;

		/* find a hugepage info with right size and increment num_pages */
		for (j = 0; j < (int) internal_config.num_hugepage_sizes; j++) {
			if (tmp_hp[i].size ==
					internal_config.hugepage_info[j].hugepage_sz) {
				internal_config.hugepage_info[j].num_pages[socket]++;
			}
		}
	}

	/* make a copy of socket_mem, needed for number of pages calculation */
	for (i = 0; i < RTE_MAX_NUMA_NODES; i++)
		memory[i] = internal_config.socket_mem[i];

	/* calculate final number of pages */
	nrpages = calc_num_pages_per_socket(memory,
			internal_config.hugepage_info, used_hp,
			internal_config.num_hugepage_sizes);

	/* error if not enough memory available */
	if (nrpages < 0)
		goto fail;

	/* reporting in! */
	for (i = 0; i < (int) internal_config.num_hugepage_sizes; i++) {
		for (j = 0; j < RTE_MAX_NUMA_NODES; j++) {
			if (used_hp[i].num_pages[j] > 0) {
				RTE_LOG(INFO, EAL,
						"Requesting %u pages of size %uMB"
						" from socket %i\n",
						used_hp[i].num_pages[j],
						(unsigned)
							(used_hp[i].hugepage_sz / 0x100000),
						j);
			}
		}
	}

	/* create shared memory */
	hugepage = create_shared_memory(eal_hugepage_info_path(),
					nrpages * sizeof(struct hugepage));

	if (hugepage == NULL) {
		RTE_LOG(ERR, EAL, "Failed to create shared memory!\n");
		goto fail;
	}

	/*
	 * unmap pages that we won't need (looks at used_hp).
	 * also, sets final_va to NULL on pages that were unmapped.
	 */
	if (unmap_unneeded_hugepages(tmp_hp, used_hp,
			internal_config.num_hugepage_sizes) < 0) {
		RTE_LOG(ERR, EAL, "Unmapping and locking hugepages failed!\n");
		goto fail;
	}

	/*
	 * copy stuff from malloc'd hugepage* to the actual shared memory.
	 * this procedure only copies those hugepages that have final_va
	 * not NULL. has overflow protection.
	 */
	if (copy_hugepages_to_shared_mem(hugepage, nrpages,
			tmp_hp, total_pages) < 0) {
		RTE_LOG(ERR, EAL, "Copying tables to shared memory failed!\n");
		goto fail;
	}

	/* free the temporary hugepage table */
	free(tmp_hp);
	tmp_hp = NULL;

	memset(mcfg->memseg, 0, sizeof(mcfg->memseg));
	j = -1;
	for (i = 0; i < nrpages; i++) {
		new_memseg = 0;

		/* if this is a new section, create a new memseg */
		if (i == 0)
			new_memseg = 1;
		else if (hugepage[i].socket_id != hugepage[i-1].socket_id)
			new_memseg = 1;
		else if (hugepage[i].size != hugepage[i-1].size)
			new_memseg = 1;
		else if ((hugepage[i].physaddr - hugepage[i-1].physaddr) !=
		    hugepage[i].size)
			new_memseg = 1;
		else if (((unsigned long)hugepage[i].final_va -
		    (unsigned long)hugepage[i-1].final_va) != hugepage[i].size)
			new_memseg = 1;

		if (new_memseg) {
			j += 1;
			if (j == RTE_MAX_MEMSEG)
				break;

			mcfg->memseg[j].phys_addr = hugepage[i].physaddr;
			mcfg->memseg[j].addr = hugepage[i].final_va;
			mcfg->memseg[j].len = hugepage[i].size;
			mcfg->memseg[j].socket_id = hugepage[i].socket_id;
			mcfg->memseg[j].hugepage_sz = hugepage[i].size;
		}
		/* continuation of previous memseg */
		else {
			mcfg->memseg[j].len += mcfg->memseg[j].hugepage_sz;
		}
		hugepage[i].memseg_id = j;
	}

	return 0;


fail:
	if (tmp_hp)
		free(tmp_hp);
	return -1;
}
Beispiel #8
0
int main(int argc, char **argv) {

    int server_fd, port_number, max_fd, file_descriptors[MAX_NUMBER_USERS], i;
    int temp_fd, select_result, timer_is_active = FALSE, status_code;

    char *validation;

    fd_set file_descriptor_set;

    check_incorrect_usage(argc, argv);
    set_log_method(argv);
    set_lock();

    port_number = extract_port_number(argv);
    server_fd = create_server(port_number, MAX_NUMBER_USERS);
    log_message("Streams server created", LOG_INFO);

    register_signal_handlers();

    for (i = 0; i < MAX_NUMBER_USERS; i++) {
        file_descriptors[i] = 0;
    }

    // -- SHARED MEMORY AND SEMAPHORES --

    shmid = create_shared_memory();
    shared_mem_ptr = attach_memory(shmid);
    init_semaphores();

    log_message("Shared memory and semaphores created", LOG_DEBUG);

    // -- SERVER LOOP --

    while (TRUE) {

        FD_ZERO(&file_descriptor_set);
        FD_SET(server_fd, &file_descriptor_set);
        max_fd = server_fd;

        for (i = 0; i < MAX_NUMBER_USERS; i++) {
            temp_fd = file_descriptors[i];

            if (temp_fd > 0) {
                FD_SET(temp_fd, &file_descriptor_set);
            }

            if (temp_fd > max_fd) {
                max_fd = temp_fd;
            }
        }

        select_result = select(max_fd + 1, &file_descriptor_set, NULL, NULL, NULL);

        if (select_result < 0 && errno != EINTR) {
            log_error("Select call error", LOG_WARNING, errno);
            continue;
        }

        if (FD_ISSET(server_fd, &file_descriptor_set)) {

            if ((temp_fd = accept(server_fd, NULL, 0)) < 0) {
                log_error("Could not accept incoming connection", LOG_ALERT, errno);
                exit(EXIT_FAILURE);
            }

            log_client_connection(temp_fd);

            for (i = 0; i < MAX_NUMBER_USERS; i++) {
                if (file_descriptors[i] != 0)
                    continue;

                file_descriptors[i] = temp_fd;
                break;
            }
        }

        for (i = 0; i < MAX_NUMBER_USERS; i++) {

            temp_fd = file_descriptors[i];

            if (!FD_ISSET(temp_fd, &file_descriptor_set))
                continue;

            char *message = NULL;
            if ((message = (char *) calloc(MESSAGE_LENGTH, sizeof(char))) == NULL) {
                log_error("Memory allocation error", LOG_ALERT, errno);
                exit(EXIT_FAILURE);
            }

            if (recv(temp_fd, message, MESSAGE_LENGTH, 0) <= 0)   // Disconnected
            {
                log_message("Client disconnected", LOG_INFO);

                close(temp_fd);
                file_descriptors[i] = 0;
            }
            else    // Message sent to server
            {
                struct message_t mess=decode(message);

                if( (status_code = mess.type) == ERROR_MESSAGE) {
                    continue;
                }

                if (get_game_phase() == REGISTER_PHASE) {

                    if (status_code != 1) {
                        // TODO Send message back to user?
                        log_message("Currently register phase. User can only register", LOG_DEBUG);
                        continue;
                    }

                    if (!timer_is_active) {
                        log_message("Starting register timer", LOG_DEBUG);
                        alarm(WAIT_TIME);
                        timer_is_active = TRUE;
                    }

                    char *new_user = (char *) malloc(MAX_ARRAY_SIZE * sizeof(char));
                    sprintf(new_user, "User '%s' asks for registration. Adding user in memory.", (char *) mess.payload);
                    log_message(new_user, LOG_INFO);

                    // Add a player to the shared memory
                    semaphore_down(SEMAPHORE_ACCESS);
                    strncpy(shared_mem_ptr->players->name, (char *) mess.payload, strlen(mess.payload));
                    shared_mem_ptr->players[i].fd = temp_fd;
                    shared_mem_ptr->players[i].score = 15; // TODO A supprimer
                    semaphore_up(SEMAPHORE_ACCESS);

                    validation = encode(VALID_REGISTRATION, "1");
                    send(temp_fd, validation, strlen(validation), 0);
                }
                else    // GAME PHASE
                {
                    log_message("Game phase. Not yet implemented.", LOG_INFO);
                }

            }
        }
    }

    return 0;
}