Exemplo n.º 1
0
RecvThread::RecvThread(QSharedPointer<QTcpSocket> sock):
    QThread()
{
    socket=sock;
    QTextCodec::setCodecForCStrings( QTextCodec::codecForName("utf8") );
    connect(socket.data(),SIGNAL(readyRead()),SLOT(readFromServer()),Qt::QueuedConnection);
}
Exemplo n.º 2
0
intrupt(fd_set * readfds)
{
  time_t  time(time_t *);
  unsigned long t;

  udcounter++;

#ifdef RECORDGAME
  if (playback)
    needredraw |= readFromFile();
  else
#endif

    needredraw |=

  readFromServer(readfds);

  t = msetime();
  if (needredraw && (t >= lastredraw + redrawDelay * 100))
    {
      lastredraw = t;
      needredraw = 0;
      lastread = time(NULL);
      redraw();

      updateMaxStats(0);       /* Update the max stats * *
              * <isae> */

#ifdef WIN32
      W_FlushScrollingWindow(messwa);
      W_FlushScrollingWindow(messwt);
      W_FlushScrollingWindow(messwi);
      W_FlushScrollingWindow(messwk);
      W_FlushScrollingWindow(reviewWin);
      W_FlushScrollingWindow(phaserwin);
#endif

      UpdatePlayerList();
    }

  if (reinitPlanets)
    {
      initPlanets();
      reinitPlanets = 0;
    }

  if (me->p_status == POUTFIT)
    {
      death();
    }
}
Exemplo n.º 3
0
int getConfiguration(int *type, char *fname, int *nThread) {
    char conf[M_SIZE];
    char *p;
    int i;
    readFromServer(conf);
    p=strtok(conf,":");
    printf("%s\n",p);
    *type=atoi(p);
    p=strtok(NULL,":");
    i=strlen(p);
    strncpy(fname, p,i);
    p=strtok(NULL,":");
    *nThread=atoi(p);

        return 0;
}
Exemplo n.º 4
0
/* Attempt to pick specified team & ship */
static int
teamRequest(int team, int ship)
{
    int     lastTime;

    extern int lastTeamReq;

    if (!playback)
	lastTeamReq = team;
    pickOk = -1;
    sendTeamReq(team, ship);
    lastTime = time(NULL);
    while (pickOk == -1) {
	if (lastTime + 3 < time(NULL)) {
	    sendTeamReq(team, ship);
	    lastTime = time(NULL);
	}
	socketPause(0, 20000);
	readFromServer();
	if (isServerDead()) {
	    printf("Whoops!  We've been ghostbusted!\n");
	    printf("Pray for a miracle!\n");

	    /* UDP fail-safe */
	    commMode = commModeReq = COMM_TCP;
	    commSwitchTimeout = 0;
	    if (udpSock >= 0)
		closeUdpConn();
	    if (udpWin) {
		udprefresh(UDP_CURRENT);
		udprefresh(UDP_STATUS);
	    }
	    connectToServer(nextSocket);
	    printf("Yea!  We've been resurrected!\n");
	    pickOk = 0;
	    break;
	}
    }

    if (pickOk) {
	me->p_status = PALIVE;	/* we got a ship.  We must be alive */
	timeBank[T_SHIP] = time(NULL);
    }
    return (pickOk);
}
Exemplo n.º 5
0
checkpassword(void)
/* Check dude's password. If he is ok, move to state ST_DONE. */
{
  char   *s;

  sendLoginReq(tempname, password1, login, 0);
  loginAccept = -1;
  while (loginAccept == -1)
    {
      socketPause();
      readFromServer(NULL);
      if (isServerDead())
  {
    printf("Server is hosed.\n");

#ifdef AUTOKEY
    if (autoKey)
      W_AutoRepeatOn();
#endif

    terminate(0);
  }
    }
  if (loginAccept == 0)
    {
      if (!autolog)
  {
    s = "Bad password!";
    W_WriteText(w, 100, 100, textColor, s, strlen(s), W_BoldFont);
    (void) W_EventsPending();
    sleep(3);
    W_ClearWindow(w);
  }
      else
  noautologin();
      *tempname = 0;
      state = ST_GETNAME;
      return;
    }
  STRNCPY(me->p_name, tempname, sizeof(tempname));
  keeppeace = (me->p_stats.st_flags / ST_KEEPPEACE) & 1;
  state = ST_DONE;
}
Exemplo n.º 6
0
FTPUpdate::FTPUpdate(QString ftpHost, QString ftpDirectory, ArpmanetDC *parent) : QObject(parent)
{
    //Constructor
    pParent = parent;
    pFtpDirectory = ftpDirectory;
    pFtpHost = ftpHost;

    downloadListIndex = -1;
    downloadGetIndex = -1;
    listIndex = -1;

    ftpServer = new QFtp(this);

    connect(ftpServer, SIGNAL(listInfo(const QUrlInfo &)), this, SLOT(listInfoReceived(const QUrlInfo &)));
    connect(ftpServer, SIGNAL(done(bool)), this, SLOT(ftpServerDone(bool)));
    connect(ftpServer, SIGNAL(commandFinished(int, bool)), this, SLOT(commandFinished(int, bool)));
    connect(ftpServer, SIGNAL(readyRead()), this, SLOT(readFromServer()));
    connect(ftpServer, SIGNAL(dataTransferProgress(qint64, qint64)), this, SIGNAL(dataTransferProgress(qint64, qint64)));
}
Exemplo n.º 7
0
RaceClient::RaceClient(QString host, int port, QObject *parent)
{
    m_host = host;
    m_port = port;

    m_socket = new QTcpSocket(this);
    m_state = RaceClient::Connecting;
    createNet(false);
    emit stateChanged(m_state);

    connect(m_socket, SIGNAL(readyRead()),
            this, SLOT(readFromServer()));

    connect(m_socket, SIGNAL(connected()),
            this, SLOT(onConnected()));

    connect(m_socket, SIGNAL(error(QAbstractSocket::SocketError)),
            this, SLOT(onError(QAbstractSocket::SocketError)));
}
Exemplo n.º 8
0
void
intrupt(void)
{
    static struct timeval lastredraw = {0, 0};
    struct timeval t;
    static int needredraw=0;

    udcounter++;
    
    needredraw += readFromServer();

    gettimeofday(&t, NULL);
    if (needredraw && ((unsigned int) redrawDelay * 100000 <
                       (unsigned int) ((t.tv_sec - lastredraw.tv_sec) * 1000000
                                       + (t.tv_usec - lastredraw.tv_usec)))) {
	needredraw = 0;
        lastredraw=t;

	if (!playback || (pb_update && 
			  ((!pb_scan) || !(udcounter % pb_advance))))
	{
	    redraw();
	    playerlist2();
	}
	if (playback) {
	    if(!pb_scan) {
		if (pb_advance > 0) {
		    if ((pb_advance -= pb_update) <= 0) {
			pb_advance = 0;
			paused = 1;
		    }
		} else if (pb_advance < 0) {
		    switch (pb_advance) {
		    case PB_REDALERT:
			if (me->p_flags & PFRED) {
			    pb_advance = 0;
			    paused = 1;
			}
			break;
		    case PB_YELLOWALERT:
			if (me->p_flags & PFYELLOW) {
			    pb_advance = 0;
			    paused = 1;
			}
			break;
		    case PB_DEATH:
		    default:
			if (me->p_status != PALIVE) {
			    pb_advance = 0;
			paused = 1;
			}
			break;
		    }
		}
	    }
	    pb_update = 0;
	}
	if (recordGame)
	    writeUpdateMarker();
    }
    if (me->p_status == POUTFIT) {
	death();
    }
}
Exemplo n.º 9
0
getname(char *defname, char *defpasswd)

/* Let person identify themselves from w */
{
  register char ch;
  int     secondsLeft = 199, laststate;
  char    tempstr[40];
  LONG    lasttime;
  char   *namptr, *passptr;
  register int j;
  struct timeval timeout;
  fd_set  readfds;

  autolog = (*defpasswd && *defname) ? 1 : 0;

  MZERO(mystats, sizeof(struct stats));

  mystats->st_tticks = 1;
  for (j = 0; j < 95; j++)
    {
      mystats->st_keymap[j] = j + 32;
      mystats->st_keymap[j + 96] = j + 32 + 96;

#ifdef MOUSE_AS_SHIFT
      mystats->st_keymap[j + 192] = j + 32;
      mystats->st_keymap[j + 288] = j + 32;
      mystats->st_keymap[j + 384] = j + 32;
#endif
    }
  mystats->st_keymap[95] = 0;
  mystats->st_flags = ST_MAPMODE + ST_NAMEMODE + ST_SHOWSHIELDS +
      ST_KEEPPEACE + ST_SHOWLOCAL * 2 + ST_SHOWGLOBAL * 2;

  lasttime = time(NULL);

  if (ghoststart)
    return;

  tempname[0] = '\0';
  password1[0] = '\0';
  password2[0] = '\0';

  laststate = state = ST_GETNAME;
  displayStartup(defname);
  while (1)
    {
      handleWEvents(defname);

      if (!autolog)
  {

#ifndef HAVE_WIN32
    W_FullScreen(baseWin);
    timeout.tv_sec = 1;
    timeout.tv_usec = 0;
#else
    /* Since we don't have a socket to check on Win32 for windowing *
     * system events, we set the timeout to zero and effectively poll.
     * * Yes, I could do the correct thing and call *
     * WaitForMultipleObjects() etc. but I don't feel like it */
    timeout.tv_sec = 0;
    timeout.tv_usec = 100000;
#endif

    FD_ZERO(&readfds);
    FD_SET(sock, &readfds);
    if (udpSock >= 0)
      FD_SET(udpSock, &readfds);

#ifndef HAVE_WIN32
    FD_SET(W_Socket(), &readfds);
#endif

    if (SELECT(32, &readfds, 0, 0, &timeout) < 0)
      {
        perror("select");
        continue;
      }

    if (FD_ISSET(sock, &readfds)
        || (udpSock >= 0 && FD_ISSET(udpSock, &readfds)))
      readFromServer(&readfds);

#ifndef HAVE_WIN32
    if (FD_ISSET(W_Socket(), &readfds))
#else
    if (W_EventsPending())
#endif

      handleWEvents(defname);
  }
      else
  {
    readFromServer(&readfds);
  }

      if (isServerDead())
  {
    printf("Shit, we were ghostbusted\n");

#ifdef HAVE_XPM
    W_GalacticBgd(GHOST_PIX);
#endif

#ifdef AUTOKEY
    if (autoKey)
      W_AutoRepeatOn();
#endif

    terminate(0);
  }

      if (time(0) != lasttime)
  {
    lasttime++;
    secondsLeft--;
    showreadme();
    if (!autolog)
      {
        sprintf(tempstr, "Seconds to go: %d ", secondsLeft);
        W_WriteText(w, 100, 400, textColor, tempstr, strlen(tempstr),
        W_RegularFont);
      }
    if (secondsLeft == 0)
      {
        me->p_status = PFREE;
        printf("Timed Out.\n");

#ifdef AUTOKEY
        if (autoKey)
    W_AutoRepeatOn();
#endif

        terminate(0);
      }
  }
      if (state == ST_DONE)
  {
    W_ClearWindow(w);
    W_ClearWindow(mapw);
    return;
  }
      if (autolog)
  {
    switch (state)
      {
      case ST_GETNAME:
        tempname[0] = '\0';
        ch = 13;
        j = 0;
        break;

      case ST_GETPASS:
      case ST_MAKEPASS1:
      case ST_MAKEPASS2:
        ch = defpasswd[j++];
        if (ch == '\0')
    {
      j = 0;
      ch = 13;
    }
        break;

      default:
        break;
      }

    loginproced(ch, defname);

  }

      laststate = state;
    }
}
Exemplo n.º 10
0
loaddude(void)
{
  char    ppwd[16];

  STRNCPY(ppwd, "\0\0\0", 4);
  if (strncmp(tempname, "Guest", 5) == 0 || strncmp(tempname, "guest", 5) == 0)
    {
      loginAccept = -1;
      sendLoginReq(tempname, ppwd, login, 0);
      state = ST_DONE;
      me->p_pos = -1;
      me->p_stats.st_tticks = 1;     /* prevent overflow */
      STRNCPY(me->p_name, tempname, sizeof(tempname));
      while (loginAccept == -1)
  {
    socketPause();
    readFromServer(NULL);
    if (isServerDead())
      {
        printf("Server is hosed.\n");

#ifdef AUTOKEY
        if (autoKey)
    W_AutoRepeatOn();
#endif

        terminate(0);
      }
  }
      if (loginAccept == 0)
  {
    char *s = "Server refuses guest login, use another name.";
    W_WriteText(w, 100, 70, textColor, s, strlen(s), W_BoldFont);
    (void) W_EventsPending();
    sleep(3);
    W_ClearWindow(w);
    state = ST_GETNAME;
    *tempname = 0;
#ifdef AUTOKEY
    if (autoKey)
      W_AutoRepeatOn();
#endif
  }
      return;
    }
  /* Ask about the user */
  loginAccept = -1;
  sendLoginReq(tempname, ppwd, login, 1);
  while (loginAccept == -1)
    {
      socketPause();
      readFromServer(NULL);
      if (isServerDead())
  {
    printf("Server is hosed.\n");

#ifdef AUTOKEY
    if (autoKey)
      W_AutoRepeatOn();
#endif

    terminate(0);
  }
    }
  *password1 = *password2 = 0;
  if (loginAccept == 0)
    {
      state = ST_MAKEPASS1;
    }
  else
    {
      state = ST_GETPASS;
    }
}
Exemplo n.º 11
0
void
new_entrywindow(int *team, int *s_type)
{
    int     i;
    int     lastplayercount[4];	/* number of players on each team */
    int     okayMask, lastOkayMask;	/* teams you're allowed to choose */
    char    buf[100];

    /* OUTFIT timeout stuff */
    long    startTime = -1;
    long    lasttime = -1;
    int     spareTime = 0;

    if (fastQuit) {
	*team = -1;
	return;
    }
    lastOkayMask = okayMask = tournMask;

    /* erase packet lights to make Bob happy [BDyess] */
    light_erase();

    /*
       map all team selection windows, and stripe out those that are
       unchoosable
    */
    for (i = 0; i < number_of_teams; i++) {
	W_MapWindow(teamWin[i]);
	lastplayercount[i] = -1;
    }
    W_MapWindow(qwin);

    /* no team selected yet */
    *team = -1;
    /*
       set to team index (0..n-1) to choose a team. set to n if you want to
       quit
    */

    /* I don't know why this restriction is in place - RF */
    if (me->p_whydead != KWINNER && me->p_whydead != KGENOCIDE) {
	showMotd(w);
	W_ClearWindow(mapw);
	showValues(mapw);
	redraw_death_messages();
    }
    do {

	/* set team to n if you want to quit */
	while (!W_EventsPending() && (me->p_status == POUTFIT ||
				      me->p_status == PTQUEUE)) {
	    /* no window events, just process socket stuff */
	    fd_set  mask;

	    light_erase();

	    readFromServer();

	    if (me->p_status == POUTFIT || me->p_status == PTQUEUE) {
		/* wait up to a half-second for input from the window system */
		struct timeval tv;

		tv.tv_sec = 0;
		tv.tv_usec = 500000;

		FD_ZERO(&mask);
		FD_SET(W_Socket(), &mask);
		select(W_Socket() + 1, &mask, 0, 0, &tv);
	    }

#if SHOW_MAP_AT_MOTD_DATA_ITEM_IMPLEMENTED
	    if(showMapAtMotd) {
		map();
	    }
#endif
	    redraw_death_messages();

	    if (me->p_status == PTQUEUE)
		startTime = -1;

	    if (me->p_status == POUTFIT) {
		/* time only elapses in OUTFIT mode */

		if (startTime == -1) {	/* we were on the tqueue */
		    /* I hate this [BDyess] */
		    W_Deiconify(baseWin);	/* we changed status.  alert
						   the user */
		    startTime = time(0);
		    spareTime = 480;	/* Allow them extra time, as long */
		    /* as they are active */
		}
		elapsed = time(0) - startTime;

		if (elapsed > autoQuit) {
		    printf("Auto-Quit.\n");
		    *team = number_of_teams;
		    break;
		}
	    }
	    if (lasttime != time(0)) {
		if (W_IsMapped(playerw))
		    playerlist2();

		if (newMotdStuff) {
		    showMotd(w);
			showValues(mapw);
		    redraw_death_messages();
		}
		if (me->p_status == POUTFIT) {
		    showTimeLeft(elapsed, autoQuit);
		}
		lasttime = time(0);
	    }
	    okayMask = tournMask;

	    /* redraw those windows whose choosable status has changed */
	    for (i = 0; i < number_of_teams; i++) {
		if ((okayMask ^ lastOkayMask) & (1 << i)) {
		    lastplayercount[i] = -1;	/* force update */
		}
		redrawTeam(teamWin[i], i, &lastplayercount[i]);
	    }
	    lastOkayMask = okayMask;
	}

	if (playback)  /* silly.  Shouldn't even be mapping team windows. */
	    break;
	/* they quit or ran out of time */
	if (*team == number_of_teams) {
	    me->p_status = PFREE;	/* exit outer while loop */
	    break;
	}
	/*
	   this makes them eventually run out of time no matter how awake
	   they are.  Only affects the OUTFIT screen.
	*/
	if (me->p_status == POUTFIT && startTime != -1) {
	    if (time(0) - startTime <= spareTime) {
		spareTime -= time(0) - startTime;
		startTime = time(0);
	    } else {
		startTime += spareTime;
		spareTime = 0;
	    }
	}
	if (!W_EventsPending())
	    continue;

	/* ok, there's a window event pending */

	/* thiswill set p_status to PFREE if they decide to quit */
	get_N_dispatch_outfit_event(team, s_type, lastplayercount);

    } while ((me->p_status == POUTFIT ||
	      me->p_status == PTQUEUE)
	     && (!pb_update)
	);

    if (*team >= 0) {
	strcpy(buf, "Welcome aboard ");
	if (paradise)
	    strcat(buf, ranks2[me->p_stats2.st_rank].name);
	else
	    strcat(buf, ranks[me->p_stats.st_rank].name);
	sprintf(buf, "Welcome aboard %s!", get_players_rank_name(me));
	warning(buf);
    }
    if (playback) {
	extern int lastTeamReq;
	*team = me->p_teami = lastTeamReq;
    } else
	/* if they quit or ran out of time */
    if (me->p_status == PFREE)
	*team = -1;
    else if (me->p_status == PALIVE ||
	     me->p_status == POBSERVE)
	if (*team == -1)
	    *team = me->p_teami;
	else
	    me->p_teami = *team;


    for (i = 0; i < number_of_teams; i++)
	W_UnmapWindow(teamWin[i]);
    W_UnmapWindow(qwin);
}
Exemplo n.º 12
0
int clientReceiveNet() {
    readFromServer(message);
        return 0;
}
Exemplo n.º 13
0
findslot(void)
{
  int     oldcount = -1;
  W_Window waitWin, qwin, countWin, motdButtonWin;

  W_Window motdWin;
  extern int MaxMotdLine;
  int     WaitMotdLine = 0;
  int     mapMotd = booleanDefault("showMotd", 1);
  W_Event event;


  /* Wait for some kind of indication about in/not in */
  while (queuePos == -1)
    {
      socketPause();
      if (isServerDead())
  {

#if defined(SOUND) && !defined(HAVE_SDL)
    Exit_Sound();
#endif

    printf("Shit!  Ghostbusted!\n");
    terminate(0);
  }
      readFromServer(NULL);
      if (me != NULL)
  {
    /* We are in! */
    ANNOUNCESOCKET;
    return (me->p_no);
  }
    }

  /* We have to wait.  Make appropriate windows, etc... */

  waitWin = W_MakeWindow("wait", 0, 0, WAITWIDTH, WAITHEIGHT, NULL, 2,
       foreColor);
  countWin = W_MakeWindow("count", WAITWIDTH / 3, WAITTITLE, WAITWIDTH / 3,
        WAITHEIGHT - WAITTITLE, waitWin, 1, foreColor);
  qwin = W_MakeWindow("waitquit", 0, WAITTITLE, WAITWIDTH / 3,
          WAITHEIGHT - WAITTITLE, waitWin, 1, foreColor);
  motdButtonWin = W_MakeWindow("motdbutton", 2 * WAITWIDTH / 3, WAITTITLE,
           WAITWIDTH / 3, WAITHEIGHT - WAITTITLE, waitWin,
             1, foreColor);
  W_MapWindow(waitWin);
  W_MapWindow(countWin);
  W_MapWindow(motdButtonWin);
  W_MapWindow(qwin);
  if (mapMotd)
    {
      motdWin = W_MakeWindow("waitmotd", 1, WAITWIDTH + 1, TWINSIDE,
           TWINSIDE, 0, 2, foreColor);
      W_MapWindow(motdWin);
      showMotd(motdWin, WaitMotdLine);
    }

  for (;;)
    {
      socketPause();
      readFromServer(NULL);
      if (isServerDead())
  {

#if defined(SOUND) && !defined(HAVE_SDL)
    Exit_Sound();
#endif

    printf("Damn, We've been ghostbusted!\n");
    terminate(0);
  }
      while (W_EventsPending())
  {
    W_NextEvent(&event);
    switch ((int) event.type)
      {
      case W_EV_BUTTON:
      case W_EV_KEY:
        if (mapMotd && event.Window == motdWin)
    {
      if (event.key == ' ' || event.key == 'q')
        {
          W_DestroyWindow(motdWin);
          mapMotd = !mapMotd;
        }
      else
        {
          if (event.key == 'b')
      {
        WaitMotdLine -= 28;
        WaitMotdLine = MAX(WaitMotdLine, 0);
      }
          else
      {
        WaitMotdLine += 28;
        /* scroll to start if it goes over */
        if (WaitMotdLine > MaxMotdLine)
          WaitMotdLine = 0;
      }
          W_ClearWindow(motdWin);
          showMotd(motdWin, WaitMotdLine);
          break;
        }
    }
        else if (event.Window == motdButtonWin)
    {
      if (mapMotd)
        {
          W_DestroyWindow(motdWin);
        }
      else
        {
          motdWin = W_MakeWindow("waitmotd", 1, WAITWIDTH + 1,
               TWINSIDE, TWINSIDE, 0, 2,
               foreColor);
          W_MapWindow(motdWin);
          showMotd(motdWin, WaitMotdLine);
        }
      mapMotd = !mapMotd;
    }
        else if (event.Window == qwin)
    {

#if defined(SOUND) && !defined(HAVE_SDL)
      Exit_Sound();
#endif

      printf("OK, bye!\n");
      terminate(0);
    }
        break;
      case W_EV_EXPOSE:
        if (event.Window == waitWin)
    {
      mapWaitWin(waitWin);
    }
        else if (event.Window == motdWin)
    {
      showMotd(motdWin, WaitMotdLine);
    }
        else if (event.Window == qwin)
    {
      mapWaitQuit(qwin);
    }
        else if (event.Window == countWin)
    {
      mapWaitCount(waitWin, countWin, queuePos);
    }
        else if (event.Window == motdButtonWin)
    {
      mapWaitMotdButton(motdButtonWin);
    }
        break;
      default:
        break;
      }
  }
      if (queuePos != oldcount)
  {
    mapWaitCount(waitWin, countWin, queuePos);
    oldcount = queuePos;
  }
      if (me != NULL)
  {
    W_DestroyWindow(waitWin);
    if (mapMotd)
      {
        W_DestroyWindow(motdWin);
      }
    ANNOUNCESOCKET;
    W_Beep();
    W_Beep();
    return (me->p_no);
  }
    }
}
Exemplo n.º 14
0
int main(int argc, char * argv[]) {
  
  killOldProcNannies();
  debugPrint("staring main\n");
  if (pipe(newProcessToChild) < 0) {
    fprintf(stderr,"pipe error");
    exit(0);
  }

  if (pipe(killCountPipe) < 0) {
    fprintf(stderr,"pipe error");
    exit(0);
  }

  fcntl(killCountPipe[0], F_SETFL, O_NONBLOCK);

  debugPrint("connecting to %s on port %d \n", argv[1], atoi(argv[2]));
  MY_PORT = atoi(argv[2]);
	
  /* Put here the name of the sun on which the server is executed */
  host = gethostbyname (argv[1]);


  int firstTime = 1;
  if (host == NULL) {
    perror ("Client: cannot get host description");
    exit (1);
  }

  s = socket (AF_INET, SOCK_STREAM, 0);

  if (s < 0) {
    perror ("Client: cannot open socket");
    exit (1);
  }

  bzero (&server, sizeof (server));
  bcopy (host->h_addr, & (server.sin_addr), host->h_length);
  server.sin_family = host->h_addrtype;
  server.sin_port = htons (MY_PORT);

  while (connect (s, (struct sockaddr*) & server, sizeof (server))) {
    perror ("Client: cannot connect to server");
    debugPrint("Tring again\n");
    //exit (1);
  }




  char * pipeBuffer = NULL;
  /* char * procInfoRequest = malloc(200); */
  /* snprintf(procInfoRequest,200, "%-200s", procInfoString); */
  /* char * a = "test\0"; */
  char a[200] = "test";
  char * processName = NULL;
  int len = 0;
  int numberofProcesses = 0;
  int processLifeSpan = 0;
  int PID = 0;
  char * pointerToProcessName = NULL;
  char * pointerToPipeBuffer = NULL;


  while (keepLooping == 1) {
    // use this loop to get process lists

    pipeBuffer = malloc(63);
    pointerToPipeBuffer = pipeBuffer;

    debugPrint("writing server\n");
    writeToServer(a);
    readFromServer(pipeBuffer);
    debugPrint("got %s\n", pipeBuffer);
    
    if (pipeBuffer[0] == '!') {
      keepLooping = 0;
      debugPrint("got exit signal!!!!!\n");
      continue;
    }

    //    char * tmpBuffer = pipeBuffer;
  
    //    char * processName;
    len = 0;
    numberofProcesses = 0;
    processLifeSpan = 0;
    PID = 0;

    len = strchr(pipeBuffer,'#') - pipeBuffer;
    processName = malloc(len+1);
    pointerToProcessName = processName;
    strncpy(processName, pipeBuffer, len);
    processName[len] = '\0'; 

    processName[strlen(processName) - 1] = '\0';

  
    pipeBuffer = strchr(pipeBuffer,'#');
    numberofProcesses = atoi(pipeBuffer+1);
    processLifeSpan = atoi(strchr(pipeBuffer,'!')+1);
    debugPrint("server: we have  %d different procs to monitor\n", numberofProcesses);

    if (processLifeSpan == 99) {
      // 99 is the code indicating that the 
      // server received a sighup
      // so flush our linked list record
      // of processes

      free(pointerToPipeBuffer);
      free(pointerToProcessName);
      pipeBuffer = NULL;
      processName = NULL;




      if (processList) {
	freeList(processList); // free it in case it is still set
	processList = NULL;
      }



      pipeBuffer = malloc(63);
      pointerToPipeBuffer = pipeBuffer;

      //      debugPrint("writing server\n");
      //      writeToServer(a); // we likely dont need to write test again cuz 
                                // our initial message should still be there
      readFromServer(pipeBuffer);
      debugPrint("got %s\n", pipeBuffer);
    
      if (pipeBuffer[0] == '!') {
	keepLooping = 0;
	debugPrint("got exit signal!!!!!\n");
	continue;
      }

      //    char * tmpBuffer = pipeBuffer;
  
      //    char * processName;
      len = 0;
      numberofProcesses = 0;
      processLifeSpan = 0;
      PID = 0;

      len = strchr(pipeBuffer,'#') - pipeBuffer;
      processName = malloc(len+1);
      pointerToProcessName = processName;
      strncpy(processName, pipeBuffer, len);
      processName[len] = '\0'; 

      processName[strlen(processName) - 1] = '\0';

  
      pipeBuffer = strchr(pipeBuffer,'#');
      numberofProcesses = atoi(pipeBuffer+1);
      processLifeSpan = atoi(strchr(pipeBuffer,'!')+1);
      debugPrint("server: we have  %d different procs to monitor\n", numberofProcesses);



    }

    free(pointerToPipeBuffer);
    free(pointerToProcessName);
    pipeBuffer = NULL;
    processName = NULL;
    //    free(processName);
    while(numberofProcesses > 0) {
      //      char * processName = NULL;
      len = 0;
      processLifeSpan = 0;
      PID = 0;
      numberofProcesses--;

      pipeBuffer = malloc(63);
      pointerToPipeBuffer = pipeBuffer;
      readFromServer(pipeBuffer);
      

      len = strchr(pipeBuffer,'#') - pipeBuffer;
      processName = malloc(len+1);
      pointerToProcessName = processName;
      //processName = (char *)realloc(processName, len+1);
      strncpy(processName, pipeBuffer, len);
      processName[len] = '\0'; 

      processName[strlen(processName) - 1] = '\0';

  
      pipeBuffer = strchr(pipeBuffer,'#');
      PID = atoi(pipeBuffer+1);
      processLifeSpan = atoi(strchr(pipeBuffer,'!')+1);


      char *newP = trimwhitespace(processName);

      debugPrint("for PID = %d\n", PID);
      debugPrint("name: %s \n", newP);
      debugPrint("life span: %d \n", processLifeSpan);
      debugPrint("pid: %d \n", PID);
      //      close (s);
      debugPrint("Process %d got %s\n", getpid (),
	       pipeBuffer);

      if (processList) { 
	if ( searchNodes(processList, newP, processLifeSpan) == -1) {
	  debugPrint("%d adding node \n", getpid());
	  addNode(processList, newP, processLifeSpan);	  
	}
      }
      else {
	debugPrint("creating process list... %d processListing node \n", getpid());
	processList = init(newP, processLifeSpan);
      }

      debugPrint("finished setting/looking thro processList\n");
      free(pointerToPipeBuffer);
      free(pointerToProcessName);
      pipeBuffer = NULL;
      processName = NULL;
    }


    sleep (5);
    updateKillCount();
    debugPrint("********************\n");

    debugPrint("number of freechildren is %d: \n", freeChildren);
    debugPrint("number of messages from children is %d: \n", messagesFromChildren);
    struct node * cursorNode;
    int i = 0;
    debugPrint("processes we monitored are: \n");
    cursorNode = monitoredPIDs;
    if (monitoredPIDs) {
      for (i = 0; i < getSize(monitoredPIDs); i++) {
	debugPrint("value: %s, key: %d\n", cursorNode->value, cursorNode->key);
	cursorNode = cursorNode->next;
      }
      
    }


    debugPrint("process we got are: \n");

    cursorNode = processList;

    for (i = 0; i < getSize(processList); i++) {
      debugPrint("for %s, %d \n",cursorNode->value, cursorNode->key);

      if (getNumberOfPIDsForProcess(cursorNode->value) > 0 || firstTime == 1) {
	debugPrint("calling monitorProcess \n");
	monitorProcess(cursorNode->value, cursorNode->key);   	
      }
      else {
	debugPrint("NOT calling monitorProcess \n");
	debugPrint("No %s proc found.\n", cursorNode->value);
      }

      cursorNode = cursorNode->next;
    }
    firstTime = 0;
    debugPrint("done listing processes in processList\n");


      
      
  }
  
  free(pipeBuffer);
  //  free(processName);
  
  freeList(processList);
  freeList(monitoredPIDs);
  freeList(childPIDs);
  return 0;
}
Exemplo n.º 15
0
Arquivo: locktests.c Projeto: 1587/ltp
void maitreClient()
{
	fd_set fdread;
	struct timeval tv;
	int n, i, r, m, start;
#ifdef DEBUG
	char dbg[16];
#endif
	struct flock lock;
	int t;

	maitreLecteur = dp.maitre[0];
	FD_ZERO(&fdread);
	tv.tv_sec = 50;
	tv.tv_usec = 0;
	n = fdServeur > maitreLecteur ? fdServeur : maitreLecteur;
	printf("Maitre CLient - fdServeur=%d\n", fdServeur);
	while (1) {
		/* On ajoute les descripteurs esclave et serveur */
		/* Add slave and server pipe file descriptors */
		FD_ZERO(&fdread);
		FD_SET(fdServeur, &fdread);
		FD_SET(maitreLecteur, &fdread);
		r = select(n + 1, &fdread, NULL, NULL, &tv);
		if (r < 0) {
			perror("select:\n");
			continue;
		}
		if (r == 0) {
			exit(0);
		}

		if (FD_ISSET(fdServeur, &fdread)) {
			/* On vient de recevoir une information du serveur
			 * On la retransmet aux esclaves
			 */
			/* We just have received information from the server.
			 * We repeat it to slaves.
			 */
			i = readFromServer(message);
			t = message[0];
			switch (t) {
			case 'L':
				/* Instruction : Lock. Dans ce cas il faut envoyer a chaque processus une section differente a locker */
				/* Lock instruction. We need to send a different section to lock to each process */

				unSerialiseFLock(&lock);
				start = lock.l_start;
				for (i = 0; i < dp.nclnt; i++) {
					lock.l_start = start + i;
					serialiseFLock(&lock);
					write(dp.lclnt[i][1], message, M_SIZE);
				}
				printf("\n");
				continue;
			case 'T':
				/* Instruction: Test. Il s'agit d'une trame annoncant un nouveau test : on verifie qu'il ne s'agit pas d'une
				 * demande de FIN des tests
				 */
				/* Test instruction. Ensure server is not sending the FIN(ish) instruction to end tests */

				/* A re-ecrire un peu mieux des que possible */
				/* To be rewritten asap */
				m = atoi(&(message[2]));
				if (m == FIN)
					break;
				if (m == CLEAN)
					printf("\n");

				serverSendLocal();
				continue;
			}
			break;
		} else {
			/* Dans le cas inverse, on lis les esclaves et on remonte l'information au serveur
			 */
			/* Else, we read information from slaves and repeat them to the server */
			for (i = 0; i < dp.nclnt; i++) {
				r = read(maitreLecteur, message, M_SIZE);
				r = write(fdServeur, message, M_SIZE);
				if (r < 0)
					perror("write : ");

			}
			continue;
		}
	}

	/* On vient de recevoir la trame FIN de programme */
	/* Receive the FIN(ish) instruction */

	/* On la communique a tous les esclaves */
	/* Repeat it to the slaves */
	printf("Fin du programme en cours...\n");
	serverSendLocal();

	/* Et c'est fini! */
	/* Ok, we can quit */
	printf("Bye :)\n");

}
Exemplo n.º 16
0
intrupt()
{
   static long     lastread;
   static int      prevread;
   int		   cr_time;

   /* handle torp firing */
   do_torps();
   _tcheck = 0;
keep_reading:
	;
#ifdef ATM
   if (readFromServer(pollmode)) {	/* should be 0 */
#else
   if (readFromServer()) {
#endif
      cr_time = mtime(0);

      _cycletime = cr_time - prevread;
      _serverdelay = ((double)_cycletime/100.);
      _udnonsync++;

      /* can't be less than 100 ms */
      if(_serverdelay < 1.) _serverdelay = 1.;

      if (DEBUG & DEBUG_SERVER) {
	 printf("cycletime = %dms\n", _cycletime);
	 printf("wait for input = %dms\n", cr_time - _waiting_for_input);
      }
      prevread = cr_time;

      if(_state.borg_detect)
	 borg_detect();
   } else {
      /*
       * We haven't heard from server for 3 secs... Strategy:  send a
       * useless packet to "ping" server.
       */
      /* If server is dead, just give up */
      if (isServerDead())
         exitRobot(0);
      if(!pollmode){
	 int	now = time(NULL)-3;
	 mprintf("sending wakeup packet at %s", ctime(&now));
	 sendWarReq(me->p_hostile);
      }
   }
   if (me->p_status == POUTFIT) {
      death();
   }
   if(me->p_status != PALIVE)
      goto keep_reading;
}

/* borg detect */

borg_detect()
{
   register Player		*p;
   register struct player	*j;
   int				last_speedc, last_dirc;
   register			i;

   for(i=0, p=_state.players; i < MAXPLAYER; i++,p++){
      if(!p->p || (p->p->p_status != PALIVE) || p->invisible)
	 continue;
      
      j = p->p;

      /* check for simultaneous torp & phaser but in different directions.
	 -- Very common borg maneuver */
      if(_udnonsync - p->tfire_t < 2){
	 if(p->tfire_t == p->pfire_t){
	    if(p->tfire_dir > -1){
	       if(angdist(p->tfire_dir, p->pfire_dir) > 2){
		  /*
		  printf("%s BORG %d\n", j->p_mapchars, 
		     angdist(p->tfire_dir, p->pfire_dir));
		  printf("current p: %d\n", p->bp1);
		  */
		  p->bp1 ++;
	       }
	    }
	 }
      }
      /* check for recent change in direction far away from current torp
	 or phaser fire */
      if(j->p_speed > 1){
	 if(_udnonsync - p->tfire_t < 2){
	    if(_udnonsync - p->turn_t < 2){
	       if(angdist(j->p_dir, p->tfire_t) > 64){
		  /*
		  printf("%s tfire BORG %d\n", j->p_mapchars,
		     angdist(j->p_dir, p->tfire_t));
		  */
		  p->bp2 ++;
	       }
	    }
	 }
	 if(_udnonsync - p->pfire_t < 2){
	    if(_udnonsync - p->turn_t < 2){
	       if(angdist(j->p_dir, p->pfire_t) > 64){
		  /*
		  printf("%s pfire BORG %d\n", j->p_mapchars,
		     angdist(j->p_dir, p->pfire_t));
		  */
		  p->bp3 ++;
	       }
	    }
	 }
      }
      if(p->bdc < 1.0)
	 p->borg_probability = 0.0;
      else
	 p->borg_probability = (double)(p->bp1 * 10 + p->bp2 + p->bp3)/
	    (double)p->bdc;
   }
}

/* maybe later */
#ifdef nodef
      if(_udcounter - p->tfire_t < 3){
	 
	 last_speedc = p->tfire_t - p->speed_t;
	 /* fired, then observed speed change within 5 cycles */
	 if(last_speedc < 5 && p->tfire_dir > -1){

	    /* player direction and torp fire direction greater than 64 */
	    if(angdist(j->p_dir, p->tfire_dir) > 64){
	       mprintf("speed detect\n");
	       p->borg_probability ++;
	    }
	 }
	 last_dirc = p->tfire_t - p->turn_t;
	 /* fired, then observed direction change within 5 cycles */
	 if(last_dirc < 5 && p->tfire_dir > -1){

	    /* player direction and torp fire direction greater than 64 */
	    if(angdist(j->p_dir, p->tfire_dir) > 64){
	       mprintf("direction detect\n");
	       p->borg_probability ++;
	    }
	 }
      }