Пример #1
0
void Wturnoff_buttons()
{
   PFI tempFunc;

   TPRINT0("Wturnoff_buttons: beginning\n");
#ifndef VNMRJ
   clearFuncs();
#endif
   linelength = 80;

   /* Mark that Wturnoff_buttons have been called.  After the
       main routine that called Wturnoff_buttons finished, the
       buttons should be cleared if Wactivate_buttons has not been
       called.  The main routine can either be initiated with a 
       button click or by entering a command in the command window.
                                                                 */
   Wturnoff_buttonsCalled = ON;

/******            Do not erase existing buttons here anymore          ********/
/*
 *#ifdef SUN
 *  if (Wissun())
 *  {  for (i=0; i<8 ;i++)
 *     {   panel_set(but[i], PANEL_SHOW_ITEM, FALSE,0);
 *     }
 *  }
 *  else
 *#endif
 *  {  Wclearpos(1,1,1,80);
 *     header[0] = NULL;
 *  }
 *  end of commented out section
 */
   buttons_active = 0;
   help_name[0] = '\0';
   if (returnFunc) /* if it exists */
   {  tempFunc = returnFunc;
      TPRINT1("Wturnoff_buttons:calling return function 0x%x\n",tempFunc);
      returnFunc = NULL;  /* Null out return function */
      (*tempFunc)();
   }
#ifndef VNMRJ
   cursorOff(BUTTONS);
   resetButtonPushed(); /* clear button pushed, so not reinversed video */
#endif
   TPRINT0("\nWturnoff_buttons: ending\n");
}
Пример #2
0
int clear_acq()
{
#ifdef NESSIE
   expStatusRelease();
#endif
   TPRINT0("clear_acq called \n");
   return(0);
}
Пример #3
0
/*------------------------------------------------------------
|
|    SendAsync2()/2
|       simplified SendAsync; make no assumptions about msge
|       connect to  an Async Process's Socket
|       then transmit a message to it and disconnect.
|
+-----------------------------------------------------------*/
int SendAsync2(CommPort to_addr, char *msge)
{
    int fgsd;   /* socket discriptor */
    int result;
    int i;
#ifndef LINUX
    int one = 1;
#endif


    if (to_addr->port == -1 || to_addr->pid == -1) /* then we do not have a socket */
       return (RET_ERROR);
    /* --- try several times then fail --- */
    for (i=0; i < MAXRETRY; i++)
    {
        fgsd = socket(AF_INET,SOCK_STREAM,0);        /* create a socket */

        if (fgsd == -1)
        {
            errLogSysRet(ErrLogOp,debugInfo,"Had trouble creating socket.");
            return(RET_ERROR);
        }
	TPRINT1("SendAsync2(): socket create for async trans %d\n",fgsd);
#ifndef LINUX
        setsockopt(fgsd,SOL_SOCKET,SO_USELOOPBACK,(const char*) &one,sizeof(one));
#endif

       /* --- attempt to connect to the named socket --- */         
       if ((result = connect(fgsd,(struct sockaddr*) &(to_addr->messname),sizeof(to_addr->messname))) != 0)
	{
	    /* --- Is Socket queue full ? --- */
	    if (errno != ECONNREFUSED && errno != ETIMEDOUT)
	    {  /* NO, some other error */
		errLogSysRet(ErrLogOp,debugInfo,"Connect error, message not sent");
	        close(fgsd);
		return(RET_ERROR);
	    }
	}                                /* Yes, try MAXRETRY times */
	else     /* connection established */
            break;
	TPRINT1("SendAsync2(): Socket queue full, will retry %d\n",i);
	close(fgsd);
	sleep(SLEEP);
    }
    if (result != 0)    /* tried MAXRETRY without success  */
    {
	errLogRet(ErrLogOp,debugInfo,"SendAsync2(): Max trys Exceeded, aborting send\n");
        return(RET_ERROR);
    }
    TPRINT0("SendAsync2(): Connection Established \n");
    write(fgsd,msge,(strlen(msge)+1));
    TPRINT1("Message Sent: %s\n",msge);

    close(fgsd);
    return(RET_OK);
}
Пример #4
0
/* made this since SendAsyncInova was also being used to communicate to Vnmr
   this fails since we changed Expproc communication scheme but not Vnmr's */
int SendAsyncInovaVnmr(CommPort to_addr, CommPort from_addr, char *msg)
{
	int	fgsd;   /* socket discriptor */
#ifndef LINUX
	int	one = 1;
#endif
        long     msgsize;

        (void) from_addr;
	if (to_addr->port == -1 || to_addr->pid == -1)
	  return (RET_ERROR);		/* then we do not have a socket */

    /* --- try several times then fail --- */

		fgsd = socket(AF_INET,SOCK_STREAM,0);	/* create a socket */

		if (fgsd == -1) {
			errLogSysRet(ErrLogOp,debugInfo,"Had trouble creating socket.");
			return(RET_ERROR);
		}
		TPRINT1("SendAsyncInovaVnmr(): socket create for async trans %d\n",fgsd);
#ifndef LINUX
		setsockopt(fgsd,SOL_SOCKET,SO_USELOOPBACK,(const void*)&one,(size_t)sizeof(one));
#endif

       /* --- attempt to connect to the named socket --- */         

		while ( (connect(fgsd,(struct sockaddr*) &(to_addr->messname),
					sizeof(to_addr->messname)) == -1)  &&
                        (errno != EISCONN) )
                {

			if (errno != EINTR)
                        {
			    /* NO, some other error */
				close(fgsd);
				return(RET_ERROR);
			}
		}

	TPRINT0("SendAsyncInovaVnmr(): Connection Established \n");

        
	msgsize = strlen(msg) + 1;	/* + 1  include null character */

	TPRINT2("SendAsyncInovaVnmr(): msgsize: %d, msge: '%s'\n",msgsize,msg);

	/* send message */
	write(fgsd,msg,msgsize);

	close(fgsd);
	return(RET_OK);
}
Пример #5
0
void init_comm_addr()
{
   CommPort ptr = &comm_addr[VNMR_COMM_ID];

   TPRINT0("init vnmr address \n");
   ptr->pid = getppid();
   ptr->port = -1;
   ptr->msg_uid = getuid();

   seteuid( ptr->msg_uid );
   strcpy(ptr->host,"");
   set_acq_id("-1");
}
Пример #6
0
int getButtonPushed(int x, int y)
{  int i;

   for (i=0; i<buttons_active; i++)
   {  if (lable[i].pixelstart <= x && x <= lable[i].pixelend)
      {
	 TPRINT1("getButtonPushed: button %d pushed\n",i+1);
	 return i+1;
      }
   }
   TPRINT0("getButtonPushed: no buttons pushed\n");
   return 0;
}
Пример #7
0
void init_comm_port(char *hostval)
{
   CommPort ptr = &comm_addr[VNMR_COMM_ID];

   TPRINT0("init vnmr port \n");
   strcpy(ptr->host,hostval);
   ptr->pid = getpid();
   ptr->msg_uid = getuid();

   seteuid( ptr->msg_uid );
   set_comm_port(ptr);

   TPRINT3("vnmr pid=%d host=%s port=%d\n",ptr->pid,ptr->host,ptr->port);
   TPRINT1("vnmr path=%s\n",ptr->path);
}
Пример #8
0
int set_comm_port(CommPort ptr)
{
   int on = 1;
   socklen_t meslength;
         TPRINT0("set vnmr port \n");

 /*===================================================================*/
 /*   ---  create the asynchronous message socket for PSG,VNMR  ---   */
 /*===================================================================*/
 
    strcpy(ptr->path,"");
    ptr->msgesocket = socket(AF_INET,SOCK_STREAM,0);  /* create a socket */
    if (ptr->msgesocket == -1)
    {
        perror("INITSOCKET(): socket error");
        exit(1);
    }   
#ifndef LINUX
    /* if on same machine, do not send out ethernet */
    setsockopt(ptr->msgesocket,SOL_SOCKET,SO_USELOOPBACK,(char*) &on,sizeof(on));
#endif
    setsockopt(ptr->msgesocket,SOL_SOCKET,(~SO_LINGER),(char *)&on,sizeof(on));
    /* close socket immediately if close request */
 
    /* --- bind a name to the socket so that others may connect to it --- */
 
   /* Use IPPORT_RESERVED +4 for port until we setup better way */
    /* Find first available port */
    ptr->messname.sin_family = AF_INET;
    ptr->port = ptr->messname.sin_port = 0; /* set to 0 for port search */
    ptr->messname.sin_addr.s_addr = INADDR_ANY;
    /* name socket */
    if (bind(ptr->msgesocket,(struct sockaddr*) &(ptr->messname),sizeof(ptr->messname)) != 0)
    {
        perror("INITSOCKET(): msgesocket bind error");
        exit(1);
    }   
    meslength = sizeof(ptr->messname);
    getsockname(ptr->msgesocket,(struct sockaddr*) &ptr->messname,&meslength);
    ptr->port = ptr->messname.sin_port;
         TPRINT1("listen of socket %d \n",ptr->msgesocket);
    listen(ptr->msgesocket,5);        /* set up listening queue ?? */

    sprintf( ptr->path, "%s %d %d", ptr->host, ptr->port, ptr->pid );
    return(0);
}
Пример #9
0
/*-----------------------------------------------------------------------
|	inVert/1
|
|	This program prints an inverted buttons
|
+-----------------------------------------------------------------------*/
void inVert(int but)
{   char *name;
    int cwindow;

    TPRINT0("inVert:starting\n");
    but--;
    name = (char *)allocateWithId(lable[but].length-1,"inVert");
    strncpy(name,lable[but].ptr,lable[but].length-1);
    name[lable[but].length-2] = '\0';
    cwindow = active;
    if (cwindow != 1) Wsetactive( 1 );
    WinverseVideo();
    Wprintfpos(1,1,lable[but].start,"%s",name);
    WnormalVideo();
    if (cwindow != 1) Wsetactive( cwindow );
    release(name);
}
Пример #10
0
int get_comm(int index, int attr, char *val)
{
   CommPort ptr = &comm_addr[index];

   if ( ptr != NULL )
   {
      if (attr == CONFIRM)
      {
	int	ival;

        TPRINT0("Confirm acq port\n");

/*  Call getAcqProcParam again, in case someone
    has done an su acqproc in the interrum	*/

#ifdef WINBRIDGE
        if (index == INFO_COMM_ID) {
            ival = getAcqProcParam(ptr, INFO_SOCKET);
        } else {
	    ival = getAcqProcParam(ptr, EXP_SOCKET);
        }
#else
        if ( (ptr->pid > 0) && ! strcmp(ptr->host,val) )
        {
	   if ( ! kill(ptr->pid,0) || (errno != ESRCH) )
              return(1);
        }
	ival = getAcqProcParam(ptr);	/* To send stuff to acq process */
#endif
	if (ival == RET_ERROR)
	  return( 0 );

        /*  check if acqPid is active */
	if (( kill(ptr->pid,0) == -1) && (errno == ESRCH))
	  return( 0 );
	else if (val != NULL)
	  return( (strcmp(ptr->host,val) == 0) );
      }
      else if (attr == ADDRESS_VNMR)
      {
         TPRINT3("get vnmr address: send %s %d %d\n",ptr->host,ptr->port,ptr->pid);
         sprintf(val, "%s %d %d", ptr->host,ptr->port,ptr->pid);
      }
      else if (attr == ADDRESS_ACQ)
      {
         TPRINT0("get acq address \n");
         if (strcmp(ptr->host,"") )
            sprintf(val, "%s %d %d", ptr->host,ptr->port,ptr->pid);
         else
            strcpy(val,"NoAcq");
      }
      else if (attr == VNMR_CONFIRM)
      {
         TPRINT0("confirm address \n");
         if (!strcmp(ptr->host,""))
            gethostname( ptr->host, sizeof( ptr->host ) );
      }
      return( 1 );
   }
   return( 0 );
}
Пример #11
0
int SendAsyncInova(CommPort to_addr, CommPort from_addr, char *msg)
{
	int	fgsd;   /* socket discriptor */
	int	result;
	int	iter;
#ifndef LINUX
	int	one = 1;
#endif
        long     msgsize;

        (void) from_addr;
	if (to_addr->port == -1 || to_addr->pid == -1)
	  return (RET_ERROR);		/* then we do not have a socket */

    /* --- try several times then fail --- */

	for (iter=0; iter < MAXRETRY; iter++) {
		fgsd = socket(AF_INET,SOCK_STREAM,0);	/* create a socket */

		if (fgsd == -1) {
			errLogSysRet(ErrLogOp,debugInfo,"Had trouble creating socket.");
			return(RET_ERROR);
		}
		TPRINT1("SendAsyncInova(): socket create for async trans %d\n",fgsd);
#ifndef LINUX
		setsockopt(fgsd,SOL_SOCKET,SO_USELOOPBACK,(const void*)&one,(size_t)sizeof(one));
#endif

       /* --- attempt to connect to the named socket --- */         
       /* retry if system interrupted */

                while ( ((result = connect(fgsd,(struct sockaddr*) &(to_addr->messname),
                                   sizeof(to_addr->messname))) != 0)  && (errno == EINTR) )
                   ;
                if (result != 0)
                {

		    /* --- Is Socket queue full ? --- */

			if (errno != ECONNREFUSED && errno != ETIMEDOUT) {

			    /* NO, some other error */

				errLogSysRet(ErrLogOp,debugInfo,"Connect error, message not sent");
				close(fgsd);
				return(RET_ERROR);
			}
		}                                /* Yes, try MAXRETRY times */
		else     /* connection established */
		  break;

		TPRINT1("SendAsyncInova(): Socket queue full, will retry %d\n",iter);
		close(fgsd);
		sleep(SLEEP);
	}
	if (result != 0) {   /* tried MAXRETRY without success  */
		errLogRet(ErrLogOp,debugInfo,"SendAsyncInova(): Max trys Exceeded, aborting send\n");
		errLogRet(ErrLogOp,debugInfo,"Problems sending message");
		return(RET_ERROR);
	}
	TPRINT0("SendAsyncInova(): Connection Established \n");

        
	msgsize = strlen(msg) + 1;	/* + 1  include null character */

	TPRINT2("SendAsyncInova(): msgsize: %d, msge: '%s'\n",msgsize,msg);
	/* TPRINT1("SendAsyncInova(): sizeof msgsize: %d, \n",sizeof(msgsize)); */
	/* TPRINT3("SendAsyncInova(): write(%d,0x%lx,%d) \n",fgsd,&msgsize,sizeof(msgsize)); */

	/* send message length */
        write(fgsd,(char*) &msgsize,sizeof(msgsize));
       
	/* send message */
	write(fgsd,msg,msgsize);
	/* TPRINT1("Message Sent: %s\n",msg); */

	close(fgsd);
	return(RET_OK);
}
Пример #12
0
void processChar(char c)
{  extern int  interuption;
   static char buffer[2048];
   static int  bp = 0;
   static int  escape = 0;
   static int  saw_escape = 0;
   static int  escape_num = 0;
#ifdef VNMRJ
   static int  show_hourglass = 0;
#endif 

   TPRINT2(1,"processChar: got %c (\\0%o)\n",
              (' ' <= c && c <= '~') ? c : ' ',c);
   if (escape && c != NEWLINE && c != CRRETURN)
   {

/*  Escape sequences must include a carriage return, so the Master
    recognizes the Child is busy, and will queue input from the
    Acqproc until the Child completes its current command.

    Thus the operation implied by the Escape Sequence is postponed
    until the Child receives a Carriage Return or New Line character.	*/

      saw_escape = 131071;
      escape_num = 10*escape_num + c-'0';
   }
   else
      switch (c)
      { case NEWLINE:
	case CRRETURN:    
			TPRINT0(1,"processChar: ...carriage return\n");
			if (saw_escape)
			{
			   saw_escape = 0;
                           escape = 0;
			   set_hourglass_cursor();
#ifdef VNMRJ
                           set_batch_function(1); // turn on graphics batch
                           setExecLevel(0);
                           newLogCmd("buttonFunc", 10);
#endif 
			   doFunction( escape_num+'0' );
#ifdef VNMRJ
                           set_batch_function(0); // turn off graphics batch
                           saveLogCmd("buttonFunc", 10);
#endif 
			   restore_original_cursor();
                           bp = 0;
			   sendReadyToMaster();
			   return;
			}
			else if (escape) {
				Werrprintf( "error in input from keyboard" );
				escape = 0;
			        saw_escape = 0;
                                bp = 0;
				sendReadyToMaster();
				return;
			}
			buffer[bp++] = '\n';
			buffer[bp++] = '\0';
			TPRINT0(2,"processChar:    saving environment\n");
			working = 1;

#ifdef VNMRJ
			if ((show_hourglass = get_hourglass(buffer)) != 0)
			   set_hourglass_cursor();
                        set_batch_function(1);
#else 
			show_hourglass = 1;
			set_hourglass_cursor();
#endif 
                        if (c == CRRETURN)
                           skipErrClear();

			/* save command history */
#ifdef VNMRJ
                        setExecLevel(0);
                        if (bp < 512) {
			    p11_writeCmdHistory(buffer); 
                            newLogCmd(buffer, bp);
                        }
		// if(okExec(buffer)) {	
                        doThisCmdHistory = doCmdHistory;
			loadAndExec(buffer);
                        if (doThisCmdHistory)
                        {
                           saveCmdHistory(buffer);
                        }
/*
if ( strncmp(buffer,"jMove",5) && strncmp(buffer,"jFunc",5) )
 */

                        set_batch_function(0);
                        if (bp < 512) {
                            saveLogCmd(buffer, bp - 2);
                        }
			
			p11_updateParamChanged();
		// }
#else 
			loadAndExec(buffer);

#endif 

                        if (show_hourglass != 0)
			    restore_original_cursor();
			Buttons_off();

			working     = 0;
			if (interuption)
			{
			   TPRINT0(2,"processChar:    Back at square one!\n");
			   interuption = 0;
			}
			else
			{
			   TPRINT0(2,"processChar:    Back again (normally)\n");
			}
			bp = 0;
			sendReadyToMaster();
			break;
	case ESC:       
			TPRINT0(1,"processChar: ...escape\n");
			escape = 1;
			escape_num = 0;
			break;
	case BACKSPACE:
	case DELETE:    
			TPRINT0(1,"processChar: ...delete\n");
			if (bp > 0)
			{  bp--;
			   putchar(BACKSPACE);
			   putchar(' ');
			   putchar(BACKSPACE);
			}
			break;
	case CONTROL_U: 
			TPRINT0(1,"processChar: ...^U\n");
			bp = 0;
			break;
	case EOF:
	case CONTROL_D: 
			TPRINT0(1,"processChar: ...end of file\n");
			nmr_exit(vnMode);
			break;
	default:	
			TPRINT1(2,"terminal_mail_loop: got %c\n",c);
			buffer[bp++] = c;
                        if (bp > 2044) {
			    buffer[bp++] = '\n';
			    buffer[bp++] = '\0';
		  	    Werrprintf( "%s", buffer);
		  	    Werrprintf( "command was too long, abort!\n" );
                            bp = 0;
                        }
			break;
      }
}
Пример #13
0
static int poke_acqproc(char *hostname, char *username,
                        int cmd, char *message )
{
    char	 acqproc_msg[ 256 ];
    int		 ival;
    int		 meslength;
    int		 on = 1;
#ifdef WINBRIDGE
    CommPort acq_addr  = &comm_addr[INFO_COMM_ID];
#else
    CommPort acq_addr  = &comm_addr[ACQ_COMM_ID];
#endif
    CommPort vnmr_addr = &comm_addr[VNMR_COMM_ID];
    CommPort tmp_from  = &comm_addr[LOCAL_COMM_ID];

        TPRINT0("Poke started \n");
    tmp_from->path[0] = '\0';
    tmp_from->pid = vnmr_addr->pid;
    strcpy(tmp_from->host,hostname);

    tmp_from->messname.sin_family = AF_INET;
    tmp_from->messname.sin_addr.s_addr = INADDR_ANY;
    tmp_from->messname.sin_port = 0;

    tmp_from->msgesocket = socket( AF_INET, SOCK_STREAM, 0 );
    if (tmp_from->msgesocket < 0) {
        acq_errno = tmp_from->msgesocket;
        return( -1 );					/*  Not ABORT !! */
    }
/* Specify socket options */
        TPRINT0("Poke socket \n");

#ifndef LINUX
    setsockopt(tmp_from->msgesocket,SOL_SOCKET,SO_USELOOPBACK,(char *)&on,sizeof(on));
#endif
    setsockopt(tmp_from->msgesocket,SOL_SOCKET,(~SO_LINGER),(char *)&on,sizeof(on));

    if (bind(tmp_from->msgesocket,(caddr_t) &(tmp_from->messname),
             sizeof(tmp_from->messname)) != 0) {
        acq_errno = BIND_ERROR;
        close( tmp_from->msgesocket );
        return( -1 );					/*  Not ABORT !! */
    }
        TPRINT0("Poke bind \n");

    meslength = sizeof(tmp_from->messname);
    getsockname(tmp_from->msgesocket,&tmp_from->messname,&meslength);
    tmp_from->port = tmp_from->messname.sin_port;
 
    listen(tmp_from->msgesocket,5);        /* set up listening queue ?? */


    sprintf( &acqproc_msg[ 0 ], "%s,%.200s", username,message);
    
#ifdef WINBRIDGE
#ifdef DEBUG    
    fprintf(stdout, "DEBUG jgw: socket.c poke_acqproc username = %s\n", username);
    fprintf(stdout, "DEBUG jgw: socket.c poke_acqproc message = %s\n", message);
    fprintf(stdout, "DEBUG jgw: socket.c poke_acqproc acq_addr->port = %d\n", acq_addr->port);
    fprintf(stdout, "DEBUG jgw: socket.c poke_acqproc cmd = %d\n", cmd);
#endif
    close( tmp_from->msgesocket );
    return( -1 );
#endif
    if (SendAsync( acq_addr, tmp_from, cmd, &acqproc_msg[ 0 ] ) == RET_ERROR )
    {
        close( tmp_from->msgesocket );
	return( -1 );
    }

/*  Use `select' to wait for Acqproc to respond to us.	*/

    ival = wait_for_select( tmp_from->msgesocket, 20 );
    if (ival < 1) {
	if (ival < 0)
		  acq_errno = SELECT_ERROR;
	else if (ival == 0)
		  acq_errno = CONNECT_ERROR;
        close( tmp_from->msgesocket );
	return( -1 );
    }
    ival = accept( tmp_from->msgesocket, 0, 0 );
    close( tmp_from->msgesocket );		/* We are finished with */
					/* the original socket. */
    if (ival < 0) {
		acq_errno = ACCEPT_ERROR;
		return( -1 );
    }
    else
	 return( ival );	/* file descriptor for the connected socket.	*/
}
Пример #14
0
void Wactivate_buttons(int number, char *name[], PFI cmd[],
                       PFI returnRoutine, char *menuname)
{
   int    i;

   TPRINT0("Wactivate_buttons: starting\n");
   if (MAX_NUM_BUTS < number)
   {  Werrprintf("Limit of %d buttons please",MAX_NUM_BUTS);
      return;
   }	
   Wturnoff_buttonsCalled = OFF; /* do not clear buttons anymore */
   clearFuncs();  /* null out previous functions */
   /* erase existing buttons */

   linelength = 80;
   header[0] = '\0';

   for (i=0;i<number;i++)
   {
      TPRINT2("Wactivate_buttons:i=%d adding %s\n",i,name[i]);
      funcs[i] = cmd[i];                 /* store function address */
      if (linelength - (int) strlen(name[i]) - 2 < 0)
      {  Werrprintf("adding %s but only %d left, buttons would run off page",
                     name[i],linelength);
	 return;
      }
   }
   if (menu_changed(number,name) )
   {
      if (Wissun())
         sendButtonToMaster( 0, NULL );
#ifndef VNMRJ
      else
         Wclearpos(1,1,1,80); /* clear top status line */
#endif 
      for (i=0;i<number;i++)
         setUpFun(name[i],i);
#ifdef VNMRJ
      sendButtonToMaster( -2, "doneButtons" ); /* button display complete */
#endif 
   }
   returnFunc = returnRoutine;  /* pointer to return function */
#ifndef VNMRJ
   if (Wisgraphon() || Wishds() || Wistek()) /* if we have terminal, print out header */
      Wprintfpos(1,1,1,"%s",header);
#endif 
   /* last argument is the name of a help file. Lets make a copy */
   strncpy(help_name,menuname,HELP_NAME_LEN);
   help_name[HELP_NAME_LEN-1] = '\0';
#ifdef DEBUG
   if (Tflag)
   {  int i;

      for (i=0; i<number; i++)
	 TPRINT2("name=%s  func = 0x%x\n",name[i],funcs[i]);
      TPRINT1("return address is 0x%x\n",returnFunc);
      TPRINT1("help file name is %s\n",help_name);
   }
#endif 
   buttons_active = num_but = number;
#ifndef VNMRJ
   cursorOn(BUTTONS);
#endif 
}
Пример #15
0
int
main(int argc, char *argv[])
{
  static AdData data;		/* to be init with 0 (debug only) */
  AdData *p_ad = &data;
  int i, user_stat = 0;

  double time_one0, time_one;
  double nb_same_var_by_iter, nb_same_var_by_iter_tot;

  int    nb_iter_cum;
  int    nb_local_min_cum;
  int    nb_swap_cum;
  int    nb_reset_cum;
  double nb_same_var_by_iter_cum;


  int    nb_restart_cum,           nb_restart_min,              nb_restart_max;
  double time_cum,                    time_min,                    time_max;

  int    nb_iter_tot_cum,          nb_iter_tot_min,             nb_iter_tot_max;
  int    nb_local_min_tot_cum,     nb_local_min_tot_min,   nb_local_min_tot_max;
  int    nb_swap_tot_cum,          nb_swap_tot_min,             nb_swap_tot_max;
  int    nb_reset_tot_cum,         nb_reset_tot_min,          nb_reset_tot_max;
  double nb_same_var_by_iter_tot_cum, nb_same_var_by_iter_tot_min, nb_same_var_by_iter_tot_max;

  int    user_stat_cum,             user_stat_min,               user_stat_max;
  char buff[256], str[32];

  /* Seeds generation */
  int last_value;	/* last value generated by the linear chaotic map */
  int param_a;		/* parameter 'a' for the linear chaotic map */
  int param_c;		/* parameter 'c' for the linear chaotic map */
  long int print_seed ;
  struct timeval tv ;
#if defined PRINT_COSTS
  char * tmp_filename=NULL ;
#endif /* PRINT_COSTS */
#if defined MPI
  Main_MPIData mpi_data ;
#endif

  Parse_Cmd_Line(argc, argv, p_ad);

  /************************ Initialize chaotic function **********************/
  param_a = 5;                      /* Values by default from research paper */
  param_c = 1;
  gettimeofday(&tv, NULL);

  /*********************** MPI & SEQ code Initialization *********************/
#if defined MPI
  mpi_data.param_a_ptr = &param_a ;
  mpi_data.param_c_ptr = &param_c ;
  mpi_data.last_value_ptr = &last_value ;
  mpi_data.p_ad = p_ad ;
  mpi_data.p_ad->main_mpi_data_ptr = &mpi_data ;
  mpi_data.print_seed_ptr = &print_seed ;
  mpi_data.tv_sec = tv.tv_sec ;
  mpi_data.count_ptr = &count ;

#if defined STATS
  Gmpi_stats.nb_sent_messages = 0 ;
  Gmpi_stats.nb_sent_mymessages = 0 ;
#endif

#if defined PRINT_COSTS
  mpi_data.nb_digits_nbprocs_ptr = &nb_digits_nbprocs ;
#endif
  MPI_Init( &argc , &argv ) ;
  MPI_Comm_rank(MPI_COMM_WORLD, &my_num) ;
  MPI_Comm_size(MPI_COMM_WORLD, &mpi_size) ;
  TPRINT0("Program: %s", argv[0]) ;
  for( i=1 ; i< argc ; ++i )
    PRINT0(" %s", argv[i]) ;
  PRINT0("\n") ;
  AS_MPI_initialization( &mpi_data ) ;
#else /****************************** MPI -> SEQ *****************************/
  TPRINT0("Program: %s", argv[0]) ;
  for( i=1 ; i< argc ; i++ )
    PRINT0(" %s", argv[i]) ;
  PRINT0("\n") ;
#if defined PRINT_COSTS
  nb_digits_nbprocs = 0 ;
#endif /* PRINT_COSTS */
  if (p_ad->seed < 0) {
    srandom((unsigned int)tv.tv_sec);
    /* INT_MAX / 6 (= 357.913.941) is a reasonable value to start with... 
       I think... */
    last_value = (int) Random(INT_MAX / 6);
    /* INT_MAX (= 2.147.483.647) is the max value for a signed 32-bit int */
    p_ad->seed = randChaos(INT_MAX, &last_value, &param_a, &param_c);
  }
  print_seed = p_ad->seed;
#endif /**************************** MPI */

#if defined PRINT_COSTS
  if( filename_pattern_print_cost==NULL ) {
    PRINT0("Please give a pattern for filename in which to save costs\n\n") ;
    exit(-1) ;
  }
  tmp_filename=(char*)
    malloc(sizeof(char)*strlen(filename_pattern_print_cost) 
	   + 2
	   + nb_digits_nbprocs ) ;
  if( nb_digits_nbprocs > 3 ) {
    PRINT0("You use a number of procs sup to 999. "
	   "You must modify the code to adjust next line\n") ;
    exit(-1) ;
  }
#if defined MPI
  /* TODO: How can we bypass the static char to format output in nxt line? */
  sprintf(tmp_filename,"%s_p%03d", filename_pattern_print_cost,my_num) ;
#else
  sprintf(tmp_filename,"%s_seq", filename_pattern_print_cost) ;
#endif
  file_descriptor_print_cost = open(tmp_filename,
				    O_WRONLY | O_EXCL | O_CREAT,
				    S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP) ;
  if( file_descriptor_print_cost == -1 ) {
    PRINTF("Cannot create file to print costs: file already exists?\n") ;
    return -1 ;
  }
#endif /* PRINT_COSTS */

  /********* Initialization of the pseudo-random generator with the seed ******/
  srandom((unsigned)p_ad->seed);

  p_ad->nb_var_to_reset = -1;
  p_ad->do_not_init = 0;
  p_ad->actual_value = NULL;
  p_ad->base_value = 0;
  p_ad->break_nl = 0;
  /* defaults */

  Init_Parameters(p_ad);

  if (p_ad->reset_limit >= p_ad->size)
    p_ad->reset_limit = p_ad->size - 1;

  setvbuf(stdout, NULL, _IOLBF, 0);
  //setlinebuf(stdout);

  if (p_ad->debug > 0 && !ad_has_debug)
    DPRINT0("Warning ad_solver is not compiled with debugging support\n") ;

  if (p_ad->log_file && !ad_has_log_file)
    DPRINT0("Warning ad_solver is not compiled with log file support\n") ;

  p_ad->size_in_bytes = p_ad->size * sizeof(int);
  p_ad->sol = malloc(p_ad->size_in_bytes);

  if (p_ad->nb_var_to_reset == -1) {
    p_ad->nb_var_to_reset = Div_Round_Up(p_ad->size * p_ad->reset_percent, 100);
    if (p_ad->nb_var_to_reset < 2) {
      p_ad->nb_var_to_reset = 2;
      PRINT0("increasing nb var to reset since too small, now = %d\n",
	     p_ad->nb_var_to_reset);
    }
  }

#if defined MPI
  AS_MPI_initialization_epilogue( &mpi_data ) ;
#endif

  /********** Print configuration information + specific initialization *****/  
  PRINT0("current random seed used: %u (seed_0 %u) \n",
	 (unsigned int)p_ad->seed, (unsigned int)print_seed) ;
  PRINT0("variables of loc min are frozen for: %d swaps\n",
	 p_ad->freeze_loc_min) ;
  PRINT0("variables swapped are frozen for: %d swaps\n", p_ad->freeze_swap) ;
  if (p_ad->reset_percent >= 0)
    PRINT0("%d %% = ", p_ad->reset_percent) ;
  PRINT0("%d variables are reset when %d variables are frozen\n", 
	 p_ad->nb_var_to_reset, p_ad->reset_limit) ;
  PRINT0("probability to select a local min (instead of "
	 "staying on a plateau): ") ;
  if (p_ad->prob_select_loc_min >=0 && p_ad->prob_select_loc_min <= 100)
    PRINT0("%d %%\n", p_ad->prob_select_loc_min) ;
  else PRINT0("not used\n") ;
  PRINT0("abort when %d iterations are reached "
	 "and restart at most %d times\n",
	 p_ad->restart_limit, p_ad->restart_max) ;

  PrintAllCompilationOptions() ;

#if defined BACKTRACK
  /* Note: This has to be done after p_ad initialization! */
  /* Gbacktrack_array_begin = 0 ; */
  /* Gbacktrack_array_end = 0 ; */
  /* Gconfiguration_size_in_bytes = p_ad->size_in_bytes ; */
  /* for( i=0 ; i<SIZE_BACKTRACK ; i++ ) */
  /*   Gbacktrack_array[i].configuration = (unsigned int*) */
  /*     malloc(Gconfiguration_size_in_bytes) ; */
  /* YC->all: do the rest of initilization */

  gl_elitePool.config_list_begin		= NULL;
  gl_elitePool.config_list_end			= NULL;
  gl_elitePool.config_list_size			= 0;
  gl_elitePool.nb_backtrack			= 0;
  gl_elitePool.nb_variable_backtrack		= 0;
  gl_elitePool.nb_value_backtrack		= 0;

  gl_stockPool.config_list_begin		= NULL;
  gl_stockPool.config_list_end			= NULL;
  gl_stockPool.config_list_size			= 0;

  backtrack_configuration *item;
  for (i = 0; i < SIZE_BACKTRACK; i++)
    {
      item			= malloc(sizeof(backtrack_configuration));
      item->configuration	= malloc(p_ad->size_in_bytes);
      pushStock(item);
    }

#endif

  TPRINT0("%d begins its resolution!\n", my_num) ;
  TPRINT0("count = %d\n", count);


  if (count <= 0) /* Note: MPI => count=1 */
    {
      Set_Initial(p_ad);

      time_one0 = (double) User_Time();
      Solve(p_ad);
      time_one = ((double) User_Time() - time_one0) / 1000;

      if (p_ad->exhaustive)
	DPRINTF("exhaustive search\n") ;
      
      if (count < 0)
	Display_Solution(p_ad);

      Verify_Sol(p_ad);

      if (p_ad->total_cost)
	PRINTF("*** NOT SOLVED (cost of this pseudo-solution: %d) ***\n", p_ad->total_cost) ;

      if (count == 0)
	{
	  nb_same_var_by_iter = (double) p_ad->nb_same_var / p_ad->nb_iter;
	  nb_same_var_by_iter_tot = (double) p_ad->nb_same_var_tot / p_ad->nb_iter_tot;

	  PRINTF("%5d %8.2f %8d %8d %8d %8d %8.1f %8d %8d %8d %8d %8.1f", 
		 p_ad->nb_restart, time_one, 
		 p_ad->nb_iter, p_ad->nb_local_min, p_ad->nb_swap, 
		 p_ad->nb_reset, nb_same_var_by_iter,
		 p_ad->nb_iter_tot, p_ad->nb_local_min_tot, p_ad->nb_swap_tot, 
		 p_ad->nb_reset_tot, nb_same_var_by_iter_tot);
	  if (user_stat_fct)
	    PRINTF(" %8d", (*user_stat_fct)(p_ad));
	  PRINTF("\n");
	}
      else
	{
	  PRINTF("in %.2f secs (%d restarts, %d iters, %d loc min, %d swaps, %d resets)\n", 
		 time_one, p_ad->nb_restart, p_ad->nb_iter_tot, p_ad->nb_local_min_tot, 
		 p_ad->nb_swap_tot, p_ad->nb_reset_tot);
	}
#if defined BACKTRACK
      PRINTF("BACKTRACK STATS:\n");
      PRINTF("Total number of performed backtracks: %d\n", gl_elitePool.nb_backtrack);
      PRINTF("Total number of performed backtracks starting from another variable: %d\n", gl_elitePool.nb_variable_backtrack);
      PRINTF("Total number of performed backtracks starting from another value: %d\n", gl_elitePool.nb_value_backtrack);
#endif
#if defined STATS
      print_stats() ;
#endif
      return 0 ;
    } /* (count <= 0) */

  if (user_stat_name)
    sprintf(str, " %8s |", user_stat_name);
  else
    *str = '\0';

  snprintf(buff, 255,
	   "|Count|restart|     time |    iters |  loc min |    swaps "
	   "|   resets | same/iter|%s\n", str);

  if (param_needed > 0)
    PRINT0("%*d\n", (int) strlen(buff)/2, p_ad->param) ;
  else if (param_needed < 0)
    PRINT0("%*s\n", (int) strlen(buff)/2, p_ad->param_file) ;

  PRINT0("%s", buff) ;
  for(i = 0; buff[i] != '\n'; ++i)
    if (buff[i] != '|')
      buff[i] = '-';
  PRINT0("%s\n", buff) ;

  nb_restart_cum = time_cum = user_stat_cum = 0;

  nb_iter_cum = nb_local_min_cum = nb_swap_cum = nb_reset_cum = 0;
  nb_same_var_by_iter_cum = user_stat_cum = 0;


  nb_iter_tot_cum = nb_local_min_tot_cum = nb_swap_tot_cum = nb_reset_tot_cum = 0;
  nb_same_var_by_iter_tot_cum = 0;

  nb_restart_min = user_stat_min = (1 << 30);
  time_min = 1e100;
  
  nb_iter_tot_min = nb_local_min_tot_min = nb_swap_tot_min = nb_reset_tot_min = (1 << 30);
  nb_same_var_by_iter_tot_min = 1e100;

  nb_restart_max = user_stat_max = 0;
  time_max = 0;
 
  nb_iter_tot_max = nb_local_min_tot_max = nb_swap_tot_max = nb_reset_tot_max = 0;
  nb_same_var_by_iter_tot_max = 0;


  for(i = 1; i <= count; i++)
    {
      Set_Initial(p_ad);

      time_one0 = (double) User_Time();
      Solve(p_ad);
      time_one = ((double) User_Time() - time_one0) / 1000;

#if !defined MPI /* Slashes MPI output! */
      if (disp_mode == 2 && nb_restart_cum > 0)
	PRINTF("\033[A\033[K");
      PRINTF("\033[A\033[K\033[A\033[256D");
#endif

      Verify_Sol(p_ad);

      if (user_stat_fct)
	user_stat = (*user_stat_fct)(p_ad);


      nb_same_var_by_iter = (double) p_ad->nb_same_var / p_ad->nb_iter;
      nb_same_var_by_iter_tot = (double) p_ad->nb_same_var_tot / p_ad->nb_iter_tot;

      nb_restart_cum += p_ad->nb_restart;
      time_cum += time_one;
      nb_iter_cum += p_ad->nb_iter;
      nb_local_min_cum += p_ad->nb_local_min;
      nb_swap_cum += p_ad->nb_swap;
      nb_reset_cum += p_ad->nb_reset;
      nb_same_var_by_iter_cum += nb_same_var_by_iter;
      user_stat_cum += user_stat;

      nb_iter_tot_cum += p_ad->nb_iter_tot;
      nb_local_min_tot_cum += p_ad->nb_local_min_tot;
      nb_swap_tot_cum += p_ad->nb_swap_tot;
      nb_reset_tot_cum += p_ad->nb_reset_tot;
      nb_same_var_by_iter_tot_cum += nb_same_var_by_iter_tot;

      if (nb_restart_min > p_ad->nb_restart)
	nb_restart_min = p_ad->nb_restart;
      if (time_min > time_one)
	time_min = time_one;
      if (nb_iter_tot_min > p_ad->nb_iter_tot)
	nb_iter_tot_min = p_ad->nb_iter_tot;
      if (nb_local_min_tot_min > p_ad->nb_local_min_tot)
	nb_local_min_tot_min = p_ad->nb_local_min_tot;
      if (nb_swap_tot_min > p_ad->nb_swap_tot)
	nb_swap_tot_min = p_ad->nb_swap_tot;
      if (nb_reset_tot_min > p_ad->nb_reset_tot)
	nb_reset_tot_min = p_ad->nb_reset_tot;
      if (nb_same_var_by_iter_tot_min > nb_same_var_by_iter_tot)
	nb_same_var_by_iter_tot_min = nb_same_var_by_iter_tot;
      if (user_stat_min > user_stat)
	user_stat_min = user_stat;

      if (nb_restart_max < p_ad->nb_restart)
	nb_restart_max = p_ad->nb_restart;
      if (time_max < time_one)
	time_max = time_one;
      if (nb_iter_tot_max < p_ad->nb_iter_tot)
	nb_iter_tot_max = p_ad->nb_iter_tot;
      if (nb_local_min_tot_max < p_ad->nb_local_min_tot)
	nb_local_min_tot_max = p_ad->nb_local_min_tot;
      if (nb_swap_tot_max < p_ad->nb_swap_tot)
	nb_swap_tot_max = p_ad->nb_swap_tot;
      if (nb_reset_tot_max < p_ad->nb_reset_tot)
	nb_reset_tot_max = p_ad->nb_reset_tot;
      if (nb_same_var_by_iter_tot_max < nb_same_var_by_iter_tot)
	nb_same_var_by_iter_tot_max = nb_same_var_by_iter_tot;
      if (user_stat_max < user_stat)
	user_stat_max = user_stat;
  
#if !defined(MPI)
      switch(disp_mode)
	{
	case 0:			/* only last iter counters */
	case 2:			/* last iter followed by restart if needed */
	  PRINTF("|%4d | %5d%c| %8.2f | %8d | %8d | %8d | %8d | %8.1f |",
		 i, p_ad->nb_restart, (p_ad->total_cost == 0) ? ' ' : 'N',
		 time_one,
		 p_ad->nb_iter, p_ad->nb_local_min, p_ad->nb_swap,
		 p_ad->nb_reset, nb_same_var_by_iter);
	  if (user_stat_fct)
	    PRINTF(" %8d |", user_stat);
	  PRINTF("\n");

	  if (disp_mode == 2 && p_ad->nb_restart > 0) 
	    {
	      PRINTF("|     |       |          |"
		     " %8d | %8d | %8d | %8d | %8.1f |",
		     p_ad->nb_iter_tot, p_ad->nb_local_min_tot,
		     p_ad->nb_swap_tot,
		     p_ad->nb_reset_tot, nb_same_var_by_iter_tot);
	      if (user_stat_fct)
		PRINTF("          |");
	      PRINTF("\n");
	    }

	  PRINTF("%s", buff);

	  PRINTF("| avg | %5d | %8.2f | %8d | %8d | %8d | %8d | %8.1f |",
		 nb_restart_cum / i, time_cum / i,
		 nb_iter_cum / i, nb_local_min_cum / i, nb_swap_cum / i,
		 nb_reset_cum / i, nb_same_var_by_iter_cum / i);
	  if (user_stat_fct)
	    PRINTF(" %8.2f |", (double) user_stat_cum / i);
	  PRINTF("\n");


	  if (disp_mode == 2 && nb_restart_cum > 0) 
	    {
	      PRINTF("|     |       |          |"
		     " %8d | %8d | %8d | %8d | %8.1f |",
		     nb_iter_tot_cum / i, nb_local_min_tot_cum / i,
		     nb_swap_tot_cum / i,
		     nb_reset_tot_cum / i, nb_same_var_by_iter_tot_cum / i);
	      if (user_stat_fct)
		PRINTF("          |");
	      PRINTF("\n");
	    }
	  break;

	case 1:			/* only total (restart + last iter) counters */
	  PRINTF("|%4d | %5d%c| %8.2f | %8d | %8d | %8d | %8d | %8.1f |",
		 i, p_ad->nb_restart, (p_ad->total_cost == 0) ? ' ' : 'N',
		 time_one,
		 p_ad->nb_iter_tot, p_ad->nb_local_min_tot, p_ad->nb_swap_tot,
		 p_ad->nb_reset_tot, nb_same_var_by_iter_tot);
	  if (user_stat_fct)
	    PRINTF(" %8d |", user_stat);
	  PRINTF("\n");

	  PRINTF("%s", buff);

	  PRINTF("| avg | %5d | %8.2f | %8d | %8d | %8d | %8d | %8.1f |",
		 nb_restart_cum / i, time_cum / i,
		 nb_iter_tot_cum / i, nb_local_min_tot_cum / i,
		 nb_swap_tot_cum / i,
		 nb_reset_tot_cum / i, nb_same_var_by_iter_tot_cum / i);
	  if (user_stat_fct)
	    PRINTF(" %8.2f |", (double) user_stat_cum / i);
	  PRINTF("\n");
	  break;
	}
#else /* MPI */
      /* disp_mode equals 1 by default */
      /* Prepare what will be sent to 0, and/or printed by 0 */
      snprintf(mpi_data.results, RESULTS_CHAR_MSG_SIZE - 1,
	       "|* %ld/(%d/%d) | %5d | %8.2f | %8d | %8d | %8d | %8d | %8.1f |",
	       print_seed,
	       my_num,
	       mpi_size,
	       nb_restart_cum / i, time_cum / i,
	       nb_iter_tot_cum / i, nb_local_min_tot_cum / i,
	       nb_swap_tot_cum / i,
	       nb_reset_tot_cum / i, nb_same_var_by_iter_tot_cum / i);
      /* TODO: use if(user_stat_fct)? What is that? */
#endif /* MPI */
    } /* for(i = 1; i <= count; i++) */

  if (count <= 0) /* YC->DD: is it really possible here? return 0 before.*/
    return 0;

  if( count > 1 ) { /* YC->DD: why this test has been removed? */
    PRINTF("| min | %5d | %8.2f | %8d | %8d | %8d | %8d | %8.1f |",
	   nb_restart_min, time_min,
	   nb_iter_tot_min, nb_local_min_tot_min, nb_swap_tot_min,
	   nb_reset_tot_min, nb_same_var_by_iter_tot_min);
    if (user_stat_fct)
      PRINTF(" %8d |", user_stat_min);
    PRINTF("\n");

    PRINTF("| max | %5d | %8.2f | %8d | %8d | %8d | %8d | %8.1f |",
	   nb_restart_max, time_max,
	   nb_iter_tot_max, nb_local_min_tot_max, nb_swap_tot_max,
	   nb_reset_tot_max, nb_same_var_by_iter_tot_max);
    if (user_stat_fct)
      PRINTF(" %8d |", user_stat_max);
    PRINTF("\n");
  }

#if defined BACKTRACK
  PRINTF("BACKTRACK STATS:\n");
  PRINTF("Total number of performed backtracks: %d\n", gl_elitePool.nb_backtrack);
  PRINTF("Total number of performed backtracks starting from another variable: %d\n", gl_elitePool.nb_variable_backtrack);
  PRINTF("Total number of performed backtracks starting from another value: %d\n", gl_elitePool.nb_value_backtrack);

  /* flush pools */
  while(gl_elitePool.config_list_size > 0)
    {
      item = popElite();
      free(item->configuration);
      free(item);
    }
  while(gl_stockPool.config_list_size > 0)
    {
      item = popStock();
      free(item->configuration);
      free(item);
    }
#endif /* BACKTRACK */

#if defined STATS
  print_stats() ;
#endif

#if !( defined MPI )
#if defined PRINT_COSTS
  print_costs() ;
#endif
  TDPRINTF("Processus ends now.\n") ;   /* Seq code is now ending */
#else /* !( defined MPI) */
  AS_MPI_completion( &mpi_data ) ;
#endif /* MPI */
}