Пример #1
0
/*{{{  main memory checking */
static void check_mem(void)
{ int	 size;
  int	 i;
  char	*buf;
  int	*wbuf;
  int	 checksum;
  int	 tmp;
  int	 failures	= 0;
  int	 iterations	= 0;

	/* Before allocating memory it is necessary to wait for the	*/
	/* various other threads to allocate their buffers.		*/
  for (i = 1; i < NumberThreads; i++)
   Wait(&ThreadsReady);

	/* Now examine the free pool to determine the amount of memory	*/
	/* to get. The system is left with 50K of memory for buffering	*/
	/* etc.								*/
  size	 = GetRoot()->FreePool->Size;
  size	-= (50 * 1024);
  size	 = (size + 1023) & ~1023;

	/* If the TFM is running on this processor reduce the memory	*/
	/* size. The TFM may need more memory as well as the kernel and	*/
	/* Processor Manager.						*/
  { Object	*tmp = Locate(NULL, "/loader/tfm");
    if (tmp != NULL)
     { size -= (50 * 1024); Close(tmp); }
    tmp = Locate(NULL, "/loader/netserv");
    if (tmp != NULL)
     { size -= (50 * 1024); Close(tmp); }
  }
    
	/* Now try to get hold of a suitable buffer. The memory may	*/
	/* be fragmented so it is necessary to try smaller and smaller	*/
	/* mallocs.							*/
  for (buf = NULL; (buf == NULL) && (size > 0); size -= (10 * 1024))
   buf = malloc(size);

  if (buf == NULL)
   { Report("main memory checker, failed to allocate a buffer");
     Wait(&ResultsLock);
     Results.OffchipMemory	= 0;
     Results.OffchipFailures	= 0;
     Signal(&ResultsLock);
     Signal(&ResultsReady);
     return;
   }

	/* Fill the buffer with random data and calculate the checksum	*/
  wbuf = (int *) buf;
  for (i = 0, checksum = 0; i < (size / sizeof(int)); i++)
   { wbuf[i]	 = hw_rand();
     checksum	+= wbuf[i];
   }

  for (iterations = 0; ; iterations++)
   { for (i = 0; (i < MemoryInterval) && !Finished; i++)
      Delay(OneSec);
     if (Finished) break;

     for (i = 0, tmp = 0; i < (size / sizeof(int)); i++)
      tmp += wbuf[i];

     if (tmp != checksum)
      { checksum = tmp; failures++; }
   }

  Wait(&ResultsLock);
  Results.OffchipMemory		= size / 1024;
  Results.OffchipFailures	= failures;
  Results.OffchipIterations	= iterations;
  Signal(&ResultsLock);
  Signal(&ResultsReady);
}
Пример #2
0
void baggingFn(int j, int bagTokenNo)						/*j is the index of the Bagger, i.e. OT[j]*/
{
    int i;							/*For the index of the Customer, i.e. C[i]*/
    int x;

    for ( x=0; x<noCustomers; x++)

        /*TO GO part*/
        if (C[x].toGoWaiting == 1 && C[x].custDoA == 1 && C[x].orderType==1)
        {

            Acquire(waitToGoLock[x]);			/*Bagger acquires the lock of Customer C[i] for the Bagger -*/

        }



    i=tokenToId[bagTokenNo];				/*Obtained Customer ID from the Bag Token No*/


    OT[j].otBagTokenNo=bagTokenNo;


    /*	while (sixBurgerAvailable < C[i].sixBurger || threeBurgerAvailable < C[i].threeBurger || veggieBurgerAvailable < C[i].veggieBurger || frenchFriesAvailable < C[i].frenchFries) currentThread -> Yield();*/

    Acquire(cookedLock);
    sixBurgerAvailable-=C[i].sixBurger;			/*The amount of food item of each type available*/
    threeBurgerAvailable-=C[i].threeBurger;			/*on its respective shelf is decremented by the number*/
    veggieBurgerAvailable-=C[i].veggieBurger;		/*of items of that type ordered by the Customer C[i]*/
    frenchFriesAvailable-=C[i].frenchFries;
    Release(cookedLock);



    if (C[i].orderType == 1)
    {

        /* *****		Monitor for TO GO Customers Begins	***** */

        if (M.mID==j) {
            Print("\nManager packed the food for Customer %d", i,0, 0);
            Print("\nManager gives food to Customer %d", i,0, 0);
            Print("\nCustomer %d receives food from the Manager\n", i, 0,0);
            Print("\nCustomer %d is leaving the restaurant after Manager packed the food\n", i, 0,0);
            Acquire(customerCounterLock);
            customerCounter++;
            Release(customerCounterLock);

        }
        else
        {
            Print("\nOrderTaker %d packed the food for Customer %d", j, i,0);
            Print("\nOrderTaker %d gives food to Customer %d", j, i,0);
            Print("\nCustomer %d receives food from the OrderTaker %d\n", i, j,0);
            Print("\nCustomer %d is leaving the restaurant after OrderTaker %d packed the food\n", i, j,0);

            Acquire(customerCounterLock);
            customerCounter++;
            Release(customerCounterLock);


        }


        if (C[i].toGoWaiting==1);
        {
            Signal(waitToGoCV[i], waitToGoLock[i]);

        }

        for (x=0; x < noCustomers; x++)			/*For each Customer*/
        {
            /*	if(waitToGoLock[x]->isHeldByCurrentThread() && x!=i)*/
            if (x !=i)
            {
                Release(waitToGoLock[x]);
            }
        }


        Wait(waitToGoCV[i], waitToGoLock[i]);
        Release(waitToGoLock[i]);


        return;							/*Exits fn*/
    }




    /* *****		Monitor for TO GO Customers Ends	***** */


    else
    {
        /*If the control reaches here, the order is Eat in type. Therefore, the Token No is appended to the waiterQueue
        	For Eat In Customers
        */

        Print("\nOrderTaker %d gives token number %d to Customer %d", C[i].myOrderTaker, C[i].custTokenNo, i);

        Acquire(waitQueueLock);				/*Ensures that only Bagger or Waiter use the queue at a time*/

        AppendList(waiterQueue, bagTokenNo);		/*The Order which needs to be bagged,
									its Token No. is appended to the waiter queue
								*/
        itemsInWaiterQueue++;

        Release(waitQueueLock);


    }


    /*return back to orderTakerFn*/



}
Пример #3
0
 WORD read_from_file(WORD pos, WORD size, char *buf, FileInfo *info)
{ int to_read;
  int sector,	  /* no of sector to read */
      first_clus, /* 1st cluster to read */
      num, 	  /* no of cluster */
      begin, 	  /* pos of 1st byte in 1st cluster */
      i,
      nb_clus, 	  /* no total of cluster to read */
      reste,
      e;

  Wait( &Var_access );
    
#ifdef debug
    IOdebug("msdosfs : read_from_file(%s), %dbytes",info->Name,size);
#endif

  if( size == 0 ) 
  {
    Signal( &Var_access );
    return 0;
  }

  first_clus = pos / Cluster_byte;
  begin      = pos % Cluster_byte;
  num        = info->Cluster;

 		/* get cluster in chain */
  
  for(i = 0; i < first_clus; i++)
  {
	num = get_fat_entry(num);
	if(num < 0)
	   goto error;
	if( num >= 0xff8 )
	{
#ifdef debugE
	   IOdebug("msdosfs ERROR : read_from_file : eof unexpected");
#endif
	   goto error;
	}
  }

		/* read up to boundary of next cluster */

  to_read = (size > (Cluster_byte - begin)) ? Cluster_byte - begin : size;
  sector = (num - 2)*Cluster_size + Dir_start + Dir_size;
  e = flop_read(sector, Cluster_byte, buf);
  for(i = 0 ; i < to_read ; i++)
	buf[i] = buf[begin + i];
  if( e < to_read )
     goto error;
  buf += to_read;

		/* read full clusters */

  nb_clus = (size-to_read)/Cluster_byte;
  for(i=0; i<nb_clus; i++)
  {
	num = get_fat_entry(num);
	if( num<0 || num>=0xff8 ) goto error;
  	sector = (num - 2)*Cluster_size + Dir_start + Dir_size;
  	if(flop_read(sector, Cluster_byte, buf) < Cluster_byte ) 
	{
          Signal( &Var_access );
	  return (i*Cluster_byte + to_read);
        }
	buf += Cluster_byte;
  }

		/* read last cluster */

  reste = size - to_read - nb_clus*Cluster_byte;
  if(reste>0)
  {
        char *freeloc;
	char *tbuff=Malloc(Cluster_byte);
	if(tbuff == NULL)
		goto error;
	freeloc = tbuff;
	num = get_fat_entry(num);
	if( num<0 || num>=0xff8 )
		{
		Free(freeloc);
		goto error;
		}
  	sector = (num - 2)*Cluster_size + Dir_start + Dir_size;
  	e = flop_read(sector, Cluster_byte, tbuff);
  	for(i = 0 ; i < reste ; i++)
		*buf++ = *tbuff++;
	Free(freeloc);
  	if( e < reste ) 
	{
          Signal( &Var_access );
	  return (nb_clus*Cluster_byte + to_read);
	}
  }

  Signal( &Var_access );
  return(size);

 error :
  Signal( &Var_access );
  return(0);

}
Пример #4
0
int
main(int argc, char **argv)
{
	int			listenfd, i, navail, maxfd, nsel, connfd, rc;
	void		sig_int(int);
	pid_t		child_make(int, int, int);
	ssize_t		n;
	fd_set		rset, masterset;
	socklen_t	addrlen, clilen;
	struct sockaddr	*cliaddr;

	if (argc == 3)
		listenfd = Tcp_listen(NULL, argv[1], &addrlen);
	else if (argc == 4)
		listenfd = Tcp_listen(argv[1], argv[2], &addrlen);
	else
		err_quit("usage: serv05 [ <host> ] <port#> <#children>");

	FD_ZERO(&masterset);
	FD_SET(listenfd, &masterset);
	maxfd = listenfd;
	cliaddr = Malloc(addrlen);

	nchildren = atoi(argv[argc-1]);
	navail = nchildren;
	cptr = Calloc(nchildren, sizeof(Child));

		/* 4prefork all the children */
	for (i = 0; i < nchildren; i++) {
		child_make(i, listenfd, addrlen);	/* parent returns */
		FD_SET(cptr[i].child_pipefd, &masterset);
		maxfd = max(maxfd, cptr[i].child_pipefd);
	}

	Signal(SIGINT, sig_int);

	for ( ; ; ) {
		rset = masterset;
		if (navail <= 0)
			FD_CLR(listenfd, &rset);	/* turn off if no available children */
		nsel = Select(maxfd, &rset, NULL, NULL, NULL);

			/* 4check for new connections */
		if (FD_ISSET(listenfd, &rset)) {
			clilen = addrlen;
			connfd = Accept(listenfd, cliaddr, &clilen);

			for (i = 0; i < nchildren; i++)
				if (cptr[i].child_status == 0)
					break;				/* available */

			if (i == nchildren)
				err_quit("no available children");
			cptr[i].child_status = 1;	/* mark child as busy */
			cptr[i].child_count++;
			navail--;

			n = Write_fd(cptr[i].child_pipefd, "", 1, connfd);
			Close(connfd);
			if (--nsel == 0)
				continue;	/* all done with select() results */
		}

			/* 4find any newly-available children */
		for (i = 0; i < nchildren; i++) {
			if (FD_ISSET(cptr[i].child_pipefd, &rset)) {
				if ( (n = Read(cptr[i].child_pipefd, &rc, 1)) == 0)
					err_quit("child %d terminated unexpectedly", i);
				cptr[i].child_status = 0;
				navail++;
				if (--nsel == 0)
					break;	/* all done with select() results */
			}
		}
	}
}
Пример #5
0
void meetCashier(int* isCashCleared, int* cash, int socialNumber) {
	int i, currentClerkIndex;

	currentClerkIndex = -1;
	while (currentClerkIndex == -1) {
		for (i = 0; i < cashierAmount; i++) {
			Acquire(cashierLocks[i]);
			if (GetMonitor(cashierClerkState[i]) == AVAILABLE) {
				currentClerkIndex = i;
				/* set clerk to busy, helping us now */
				SetMonitor(cashierClerkState[i], BUSY);
				break;
			} else { /* either on break or busy, can't do anything with this clerk atm */
				Release(cashierLocks[i]);
			}
		}
		if (currentClerkIndex == -1) {
			punish(10,100); /* wait a little bit, someone will be available soon */
		}
	}
	
	Write("Senator ", 8, ConsoleOutput);
	WriteInt(socialNumber);
	Write(" has gotten in regular line for CashierClerk ", sizeof(" has gotten in regular line for CashierClerk "), ConsoleOutput);
	WriteInt(currentClerkIndex);
	Write("\n", 1, ConsoleOutput);

	/* customer is at cashier now */
	SetMonitor(cashierDB[currentClerkIndex], socialNumber);

	Write("Senator ", 8, ConsoleOutput);
	WriteInt(socialNumber);
	Write(" has given SSN ", sizeof(" has given SSN "), ConsoleOutput);
	WriteInt(socialNumber);
	Write(" to cashier ", sizeof(" to cashier "), ConsoleOutput);
	WriteInt(currentClerkIndex);
	Write("\n", 1, ConsoleOutput);

	Signal(cashierCV[currentClerkIndex], cashierLocks[currentClerkIndex]);
	Wait(cashierCV[currentClerkIndex], cashierLocks[currentClerkIndex]);

	if (GetMonitor(cashierDBCleared[currentClerkIndex])){
		/* that means cashier is notified that the previous */
		/* requirements have been completed and is cleared to continue */
		/* for user to pay and get checked off */
		
		Write("Senator ", 8, ConsoleOutput);
		WriteInt(socialNumber);
		Write(" has given Cashier ", sizeof(" has given Cashier "), ConsoleOutput);
		WriteInt(currentClerkIndex);
		Write(" $100", sizeof(" $100"), ConsoleOutput);
		Write("\n", 1, ConsoleOutput);

		*cash -= 100;
		*isCashCleared = TRUE;
		Release(cashierLocks[currentClerkIndex]);
	} else {
		/* customer should NOT be here, punish the user */		
		Write("Senator ", 8, ConsoleOutput);
		WriteInt(socialNumber);
		Write(" has gone to Cashier ", sizeof(" has gone to Cashier "), ConsoleOutput);
		WriteInt(currentClerkIndex);
		Write(" too soon. They are going to the back of the line.", sizeof(" too soon. They are going to the back of the line."), ConsoleOutput);
		Write("\n", 1, ConsoleOutput);

		Release(cashierLocks[currentClerkIndex]);
		punish(100, 1000);
	}
}
Пример #6
0
static __saveds void net_func(void)
{
	const char *str;
	BYTE od_error;
	struct MsgPort *write_port = NULL, *control_port = NULL;
	struct IOSana2Req *write_io = NULL, *control_io = NULL;
	bool opened = false;
	ULONG read_mask = 0, write_mask = 0, proc_port_mask = 0;
	struct Sana2DeviceQuery query_data = {sizeof(Sana2DeviceQuery)};
	ULONG buffer_tags[] = {
		S2_CopyToBuff, (uint32)copy_to_buff,
		S2_CopyFromBuff, (uint32)copy_from_buff,
		TAG_END
	};

	// Default: error occured
	proc_error = true;

	// Create message port for communication with main task
	proc_port = CreateMsgPort();
	if (proc_port == NULL)
		goto quit;
	proc_port_mask = 1 << proc_port->mp_SigBit;

	// Create message ports for device I/O
	read_port = CreateMsgPort();
	if (read_port == NULL)
		goto quit;
	read_mask = 1 << read_port->mp_SigBit;
	write_port = CreateMsgPort();
	if (write_port == NULL)
		goto quit;
	write_mask = 1 << write_port->mp_SigBit;
	control_port = CreateMsgPort();
	if (control_port == NULL)
		goto quit;

	// Create control IORequest
	control_io = (struct IOSana2Req *)CreateIORequest(control_port, sizeof(struct IOSana2Req));
	if (control_io == NULL)
		goto quit;
	control_io->ios2_Req.io_Message.mn_Node.ln_Type = 0;	// Avoid CheckIO() bug

	// Parse device name
	char dev_name[256];
	ULONG dev_unit;

	str = PrefsFindString("ether");
	if (str) {
		const char *FirstSlash = strchr(str, '/');
		const char *LastSlash = strrchr(str, '/');

		if (FirstSlash && FirstSlash && FirstSlash != LastSlash) {

			// Device name contains path, i.e. "Networks/xyzzy.device"
			const char *lp = str;
			char *dp = dev_name;

			while (lp != LastSlash)
				*dp++ = *lp++;
			*dp = '\0';

			if (strlen(dev_name) < 1)
				goto quit;

			if (sscanf(LastSlash, "/%ld", &dev_unit) != 1)
				goto quit;
		} else {
			if (sscanf(str, "%[^/]/%ld", dev_name, &dev_unit) != 2)
				goto quit;
		}
	} else
		goto quit;

	// Open device
	control_io->ios2_BufferManagement = buffer_tags;
	od_error = OpenDevice((UBYTE *) dev_name, dev_unit, (struct IORequest *)control_io, 0);
	if (od_error != 0 || control_io->ios2_Req.io_Device == 0) {
		printf("WARNING: OpenDevice(<%s>, unit=%d) returned error %d)\n", (UBYTE *)dev_name, dev_unit, od_error);
		goto quit;
	}
	opened = true;

	// Is it Ethernet?
	control_io->ios2_Req.io_Command = S2_DEVICEQUERY;
	control_io->ios2_StatData = (void *)&query_data;
	DoIO((struct IORequest *)control_io);
	if (control_io->ios2_Req.io_Error)
		goto quit;
	if (query_data.HardwareType != S2WireType_Ethernet) {
		WarningAlert(GetString(STR_NOT_ETHERNET_WARN));
		goto quit;
	}

	// Yes, create IORequest for writing
	write_io = (struct IOSana2Req *)CreateIORequest(write_port, sizeof(struct IOSana2Req));
	if (write_io == NULL)
		goto quit;
	memcpy(write_io, control_io, sizeof(struct IOSana2Req));
	write_io->ios2_Req.io_Message.mn_Node.ln_Type = 0;	// Avoid CheckIO() bug
	write_io->ios2_Req.io_Message.mn_ReplyPort = write_port;

	// Configure Ethernet
	control_io->ios2_Req.io_Command = S2_GETSTATIONADDRESS;
	DoIO((struct IORequest *)control_io);
	memcpy(ether_addr, control_io->ios2_DstAddr, 6);
	memcpy(control_io->ios2_SrcAddr, control_io->ios2_DstAddr, 6);
	control_io->ios2_Req.io_Command = S2_CONFIGINTERFACE;
	DoIO((struct IORequest *)control_io);
	D(bug("Ethernet address %08lx %08lx\n", *(uint32 *)ether_addr, *(uint16 *)(ether_addr + 4)));

	// Initialization went well, inform main task
	proc_error = false;
	Signal(MainTask, SIGF_SINGLE);

	// Main loop
	for (;;) {

		// Wait for I/O and messages (CTRL_C is used for quitting the task)
		ULONG sig = Wait(proc_port_mask | read_mask | write_mask | SIGBREAKF_CTRL_C);

		// Main task wants to quit us
		if (sig & SIGBREAKF_CTRL_C)
			break;

		// Main task sent a command to us
		if (sig & proc_port_mask) {
			struct NetMessage *msg;
			while (msg = (NetMessage *)GetMsg(proc_port)) {
				D(bug("net_proc received %08lx\n", msg->what));
				switch (msg->what) {
					case MSG_CLEANUP:
						remove_all_protocols();
						break;

					case MSG_ADD_MULTI:
						control_io->ios2_Req.io_Command = S2_ADDMULTICASTADDRESS;
						Mac2Host_memcpy(control_io->ios2_SrcAddr, msg->pointer + eMultiAddr, 6);
						DoIO((struct IORequest *)control_io);
						if (control_io->ios2_Req.io_Error == S2ERR_NOT_SUPPORTED) {
							WarningAlert(GetString(STR_NO_MULTICAST_WARN));
							msg->result = noErr;
						} else if (control_io->ios2_Req.io_Error)
							msg->result = eMultiErr;
						else
							msg->result = noErr;
						break;

					case MSG_DEL_MULTI:
						control_io->ios2_Req.io_Command = S2_DELMULTICASTADDRESS;
						Mac2Host_memcpy(control_io->ios2_SrcAddr, msg->pointer + eMultiAddr, 6);
						DoIO((struct IORequest *)control_io);
						if (control_io->ios2_Req.io_Error)
							msg->result = eMultiErr;
						else
							msg->result = noErr;
						break;

					case MSG_ATTACH_PH: {
						uint16 type = msg->type;
						uint32 handler = msg->pointer;

						// Protocol of that type already installed?
						NetProtocol *p = (NetProtocol *)prot_list.lh_Head, *next;
						while ((next = (NetProtocol *)p->ln_Succ) != NULL) {
							if (p->type == type) {
								msg->result = lapProtErr;
								goto reply;
							}
							p = next;
						}

						// Allocate NetProtocol, set type and handler
						p = (NetProtocol *)AllocMem(sizeof(NetProtocol), MEMF_PUBLIC);
						if (p == NULL) {
							msg->result = lapProtErr;
							goto reply;
						}
						p->type = type;
						p->handler = handler;

						// Set up and submit read requests
						for (int i=0; i<NUM_READ_REQUESTS; i++) {
							memcpy(p->read_io + i, control_io, sizeof(struct IOSana2Req));
							p->read_io[i].ios2_Req.io_Message.mn_Node.ln_Name = (char *)p;	// Hide pointer to NetProtocol in node name
							p->read_io[i].ios2_Req.io_Message.mn_Node.ln_Type = 0;			// Avoid CheckIO() bug
							p->read_io[i].ios2_Req.io_Message.mn_ReplyPort = read_port;
							p->read_io[i].ios2_Req.io_Command = CMD_READ;
							p->read_io[i].ios2_PacketType = type;
							p->read_io[i].ios2_Data = p->read_buf[i];
							p->read_io[i].ios2_Req.io_Flags = SANA2IOF_RAW;
							BeginIO((struct IORequest *)(p->read_io + i));
						}

						// Add protocol to list
						AddTail(&prot_list, p);

						// Everything OK
						msg->result = noErr;
						break;
					}

					case MSG_DETACH_PH: {
						uint16 type = msg->type;
						msg->result = lapProtErr;
						NetProtocol *p = (NetProtocol *)prot_list.lh_Head, *next;
						while ((next = (NetProtocol *)p->ln_Succ) != NULL) {
							if (p->type == type) {
								remove_protocol(p);
								msg->result = noErr;
								break;
							}
							p = next;
						}
						break;
					}

					case MSG_WRITE: {
						// Get pointer to Write Data Structure
						uint32 wds = msg->pointer;
						write_io->ios2_Data = (void *)wds;

						// Calculate total packet length
						long len = 0;
						uint32 tmp = wds;
						for (;;) {
							int16 w = ReadMacInt16(tmp);
							if (w == 0)
								break;
							len += w;
							tmp += 6;
						}
						write_io->ios2_DataLength = len;

						// Get destination address
						uint32 hdr = ReadMacInt32(wds + 2);
						Mac2Host_memcpy(write_io->ios2_DstAddr, hdr, 6);

						// Get packet type
						uint32 type = ReadMacInt16(hdr + 12);
						if (type <= 1500)
							type = 0;		// 802.3 packet
						write_io->ios2_PacketType = type;

						// Multicast/broadcard packet?
						if (write_io->ios2_DstAddr[0] & 1) {
							if (*(uint32 *)(write_io->ios2_DstAddr) == 0xffffffff && *(uint16 *)(write_io->ios2_DstAddr + 4) == 0xffff)
								write_io->ios2_Req.io_Command = S2_BROADCAST;
							else
								write_io->ios2_Req.io_Command = S2_MULTICAST;
						} else
							write_io->ios2_Req.io_Command = CMD_WRITE;

						// Send packet
						write_done = false;
						write_io->ios2_Req.io_Flags = SANA2IOF_RAW;
						BeginIO((IORequest *)write_io);
						break;
					}
				}
reply:			D(bug(" net_proc replying\n"));
				ReplyMsg(msg);
			}
		}

		// Packet received
		if (sig & read_mask) {
			D(bug(" packet received, triggering Ethernet interrupt\n"));
			SetInterruptFlag(INTFLAG_ETHER);
			TriggerInterrupt();
		}

		// Packet write completed
		if (sig & write_mask) {
			GetMsg(write_port);
			WriteMacInt32(ether_data + ed_Result, write_io->ios2_Req.io_Error ? excessCollsns : 0);
			write_done = true;
			D(bug(" packet write done, triggering Ethernet interrupt\n"));
			SetInterruptFlag(INTFLAG_ETHER);
			TriggerInterrupt();
		}
	}
quit:

	// Close everything
	remove_all_protocols();
	if (opened) {
		if (CheckIO((struct IORequest *)write_io) == 0) {
			AbortIO((struct IORequest *)write_io);
			WaitIO((struct IORequest *)write_io);
		}
		CloseDevice((struct IORequest *)control_io);
	}
	if (write_io)
		DeleteIORequest(write_io);
	if (control_io)
		DeleteIORequest(control_io);
	if (control_port)
		DeleteMsgPort(control_port);
	if (write_port)
		DeleteMsgPort(write_port);
	if (read_port)
		DeleteMsgPort(read_port);

	// Send signal to main task to confirm termination
	Forbid();
	Signal(MainTask, SIGF_SINGLE);
}
Пример #7
0
LONG launcher()
{
    D(bug("launcher: Entered child launcher\n"));

    struct Task *this = FindTask(NULL);
    struct vfork_data *udata = this->tc_UserData;
    BYTE child_signal;
    struct Library *aroscbase = NULL;

    GetIntETask(this)->iet_startup = GetETask(this)->et_Result2 = AllocVec(sizeof(struct aros_startup), MEMF_ANY | MEMF_CLEAR);

    /* Allocate signal for parent->child communication */
    child_signal = udata->child_signal = AllocSignal(-1);
    D(bug("launcher: Allocated child signal: %d\n", udata->child_signal));
    if(udata->child_signal == -1)
    {
	/* Lie */
	udata->child_errno = ENOMEM;
	Signal(udata->parent, 1 << udata->parent_signal);
	return -1;
    }

    if(__register_init_fdarray(udata->ppriv->acpd_fd_array, udata->ppriv->acpd_numslots))
        aroscbase = OpenLibrary((STRPTR) "arosc.library", 0);
    if(!aroscbase)
    {
	FreeSignal(child_signal);
	udata->child_errno = ENOMEM;
	Signal(udata->parent, 1 << udata->parent_signal);
	return -1;	
    }
    
    udata->cpriv = __get_arosc_privdata();
    udata->cpriv->acpd_parent_does_upath = udata->ppriv->acpd_doupath;
    udata->cpriv->acpd_flags |= DO_NOT_CLONE_ENV_VARS;

    if(setjmp(__aros_startup_jmp_buf) == 0)
    {
        /* Setup complete, signal parent */
        D(bug("launcher: Signaling parent that we finished setup\n"));
        Signal(udata->parent, 1 << udata->parent_signal);

        D(bug("launcher: Child waiting for exec or exit\n"));
        Wait(1 << udata->child_signal);

        if(udata->child_executed)
        {
            APTR exec_id;
            BPTR dir;
            
            D(bug("launcher: child executed\n"));
            
            /* Set current dir to parent's current dir */
            dir = DupLock(((struct Process *)udata->parent)->pr_CurrentDir);
            UnLock(CurrentDir(dir));
            /* Don't mind updating aroscbase->acb_startup_cd_changed as we will
               exit from process after __exec_do has finished */

            /* Filenames passed from parent obey parent's __doupath */
            __doupath = udata->cpriv->acpd_parent_does_upath;
            D(bug("launcher: __doupath == %d for __exec_prepare()\n", __doupath));
            
            exec_id = udata->exec_id = __exec_prepare(
                udata->exec_filename,
                udata->exec_searchpath,
                udata->exec_argv,
                udata->exec_envp
            );
            
            udata->child_errno = errno;

            /* Clear __doupath again, command will set it if wanted */
            __doupath = 0;
            
            D(bug("launcher: informing parent that we have run __exec_prepare\n"));
            /* Inform parent that we have run __exec_prepare */
            Signal(udata->parent, 1 << udata->parent_signal);
            
            /* Wait 'till __exec_do() is called on parent process */
            D(bug("launcher: Waiting parent to get the result\n"));
            Wait(1 << udata->child_signal);

            D(bug("launcher: informing parent that we won't use udata anymore\n"));
            /* Inform parent that we won't use udata anymore */
            Signal(udata->parent, 1 << udata->parent_signal);

            if (exec_id)
            {
                D(bug("launcher: executing command\n"));
                __exec_do(exec_id);
                
                assert(0); /* Should not be reached */
            }
            else
            {
                D(bug("launcher: exit because execve returned with an error\n"));
                _exit(0);
            }
        }
        else
        {
            D(bug("launcher: informing parent that we won't use udata anymore\n"));
            /* Inform parent that we won't use udata anymore */
            Signal(udata->parent, 1 << udata->parent_signal);
        }
    }
    else
    {
        D(bug("launcher: freeing child_signal\n"));
        FreeSignal(child_signal);
        CloseLibrary(aroscbase);
    }
    
    return 0;
}
Пример #8
0
void startManager() {
#define cis Airlines[i]._cis[j]
	int i, j; /* for-loop iterator */
	while (true) {
		int numReadyAirlines = 0;
		/*
			Check-in Staff 
		*/
		if (!Manager._allCISDone) {
			int numDoneAirline = 0;
			for (i = 0; i < NUM_AIRLINES; ++i) {
				if (!Airlines[i]._CISclosed) {
					Acquire(Airlines[i]._lock);
					if (Airlines[i]._numCheckedinPassengers == Airlines[i]._numExpectedPassengers){
						if (Airlines[i]._numOnBreakCIS == NUM_CIS_PER_AIRLINE) {
							/* All Passenger have JUST went through, send CIS home */
							Release(Airlines[i]._lock); /* TODO is this necessary? */
							numDoneAirline++;
							for (j = 0; j < NUM_CIS_PER_AIRLINE; ++j) {
								/*Acquire(cis._lock);*/
								cis._done = true;
								Signal(Airlines[i]._lock, cis._commCV);
								/*Release(cis._lock);*/
							}
							Airlines[i]._CISclosed = true;
						} else {
							Release(Airlines[i]._lock); /* TODO is this necessary? */
						}
					} else {
						/* There are still passengers to serve */
						Release(Airlines[i]._lock);/* TODO is this necessary? */
						for (j = 0; j < NUM_CIS_PER_AIRLINE; ++j) {
							Acquire(Airlines[i]._cisLineLock);
							Acquire(Airlines[i]._execLineLock);
							Acquire(cis._lock);
							if ((!queue_empty(&Airlines[i]._execQueue) || cis._lineSize) && cis._state == ONBREAK) {
/*								Signal(cis._lock, cis._commCV);*/
								Signal(Airlines[i]._lock, cis._commCV);
							}
							Release(cis._lock);
							Release(Airlines[i]._execLineLock);
							Release(Airlines[i]._cisLineLock);
						}
					}
				} else {
					numDoneAirline++;
				}	
			}
			if (numDoneAirline == NUM_AIRLINES) {
				Manager._allCISDone = true;
				/* Exit all Liaisons too! */
				/* If all CIS are done, so are all Liaisons */
				Manager._allLiaisonsDone = true;
				for(i = 0; i < NUM_LIASONS; ++i) {
					Signal(Liaisons[i]._lock, Liaisons[i]._commCV);
				}
			} else {
				Manager._allCISDone = false;
			}
		} /* end if(!_allCISDone) */
#undef cis
		/* end CIS */

		/*
			Check Conveyor Belt - Cargo Handlers
		*/
		if (!Manager._allCargoDone) {
			int numDone = 0;
			bool msgToCargo = true;

			Acquire(ConveyorLock);
			for (i = 0; i < NUM_AIRLINES; ++i) {
/*Printf1("Number loaded: %d, number expected: %d\n", sizeof("Number loaded: %d, number expected: %d\n"), concat2Num(Airlines[i]._numExpectedBaggages, Airlines[i]._numLoadedBaggages));*/
				if (Airlines[i]._numExpectedBaggages == Airlines[i]._numLoadedBaggages) {
					numDone++;
				}
			}
			if (numDone == NUM_AIRLINES) {
/*Printf0("All Cargo Handlers done!\n", sizeof("All Cargo Handlers done!\n"));*/
				Manager._allCargoDone = true;
				for (i = 0; i < NUM_CARGO_HANDLERS; ++i) {
					Signal(ConveyorLock, CargoHandlers[i]._commCV);
				}
			}
			for (i = 0; i < NUM_CARGO_HANDLERS; ++i) {
				if (!queue_empty(&ConveyorBelt) && CargoHandlers[i]._state == ONBREAK) {
					Signal(ConveyorLock, CargoHandlers[i]._commCV);

					if (msgToCargo) {
						Printf0("Airport manager calls back all the cargo handlers from break\n",
							sizeof("Airport manager calls back all the cargo handlers from break\n"));
						msgToCargo = false;
					}
				}
			}
			Release(ConveyorLock);
		}
		/* end Conveyor Belt / Cargo Handlers */

		/*
			Security Officers
		*/
		Acquire(OfficersLineLock);
		for (i = 0; i < NUM_SCREENING_OFFICERS; ++i) {
			if (!queue_empty(&OfficersLine) && ScreeningOfficers[i]._state == ONBREAK) {
				Signal(OfficersLineLock, ScreeningOfficers[i]._commCV);
			}
		}
		Release(OfficersLineLock);
		/* end Security Officers */

		/*
			Check Boarding Lounge
		*/
		for (i = 0; i < NUM_AIRLINES; ++i) {
			if (Airlines[i]._boarded) {
				numReadyAirlines++;
			} else if(Airlines[i]._numExpectedBaggages == Airlines[i]._numLoadedBaggages
				&& Airlines[i]._numExpectedPassengers == Airlines[i]._numReadyPassengers) {
				Printf1("Airport manager gives a boarding call to airline %d\n",
					sizeof("Airport manager gives a boarding call to airline %d\n"),
					i);
				for (j = 0; j < Airlines[i]._numReadyPassengers; ++j) {
					Acquire(Airlines[i]._lock);
					Signal(Airlines[i]._lock, Airlines[i]._boardLoungeCV);
					Release(Airlines[i]._lock);
				}
				numReadyAirlines++;
				Airlines[i]._boarded = true;
			}
		}

		if (numReadyAirlines == NUM_AIRLINES) {
			int pass_cnt_liaisons = 0;
			int pass_cnt_SI = 0;
			int pass_cnt_CIS = 0;
			int bag_cnt_liaison = 0;
			int bag_cnt_cargo = 0;
			int weight_cnt_CIS = 0;
			int weight_cnt_cargo = 0;

			Printf0("=====================STATS======================\n", sizeof("=====================STATS======================\n"));

			for (i = 0; i < NUM_LIASONS; ++i) {
				for (j = 0; j < NUM_AIRLINES; ++j) {
					pass_cnt_liaisons += Liaisons[i]._passCount[j];
				}
			}
			Printf1("Passenger count reported by airport liaison = %d\n",
				sizeof("Passenger count reported by airport liaison = %d\n"),
				pass_cnt_liaisons);

			for (i = 0; i < NUM_AIRLINES; ++i) {	
				for (j = 0; j < NUM_CIS_PER_AIRLINE; ++j) {
					pass_cnt_CIS += Airlines[i]._cis[j]._passCount;
				}
			}
			Printf1("Passenger count reported by airline check-in staff = %d\n",
				sizeof("Passenger count reported by airline check-in staff = %d\n"),
				pass_cnt_CIS);

			for (i = 0; i < NUM_SECURITY_INSPECTORS; ++i) {	
				pass_cnt_SI += SecurityInspectors[i]._passCount;
			}
			Printf1("Passenger count reported by security inspector = %d\n",
				sizeof("Passenger count reported by security inspector = %d\n"),
				pass_cnt_SI);

			for (i = 0; i < NUM_AIRLINES; ++i) {	
				Printf1("From setup: Baggage count of airline %d = %d\n",
					sizeof("From setup: Baggage count of airline %d = %d\n"),
					concat2Num(i, Airlines[i]._numExpectedBaggages));
			}

			for (i = 0; i < NUM_AIRLINES; ++i) {	
				bag_cnt_liaison = 0;
				for (j = 0; j < NUM_LIASONS; ++j) {	
					bag_cnt_liaison += Liaisons[j]._bagCount[i];
				}
				Printf1("From airport liaison: Baggage count of airline %d = %d\n",
					sizeof("From airport liaison: Baggage count of airline %d = %d\n"),
					concat2Num(i, bag_cnt_liaison));
			}	

			for (i = 0; i < NUM_AIRLINES; ++i) {
				bag_cnt_cargo = 0;
				for (j = 0; j < NUM_CARGO_HANDLERS; ++j) {	
					bag_cnt_cargo += CargoHandlers[j]._bagCount[i];
				}
				Printf1("From cargo handlers: Baggage count of airline %d = %d\n",
					sizeof("From cargo handlers: Baggage count of airline %d = %d\n"),
				 	concat2Num(i, bag_cnt_cargo));
			}

			for (i = 0; i < NUM_AIRLINES; ++i) {
				Printf1("From setup: Baggage weight of airline %d = %d\n",
					sizeof("From setup: Baggage weight of airline %d = %d\n"),
					concat2Num(i, Airlines[i]._weightCount));
			}

			for (i = 0; i < NUM_AIRLINES; ++i) {
				weight_cnt_CIS = 0;
				for (j = 0; j < NUM_CIS_PER_AIRLINE; ++j) {
					weight_cnt_CIS += Airlines[i]._cis[j]._weightCount;
				}
				Printf1("From airline check-in staff: Baggage weight of airline %d = %d\n",
					sizeof("From airline check-in staff: Baggage weight of airline %d = %d\n"),
					concat2Num(i, weight_cnt_CIS));
			}

			for (i = 0; i < NUM_AIRLINES; ++i) {
				weight_cnt_cargo = 0;
				for (j = 0; j < NUM_CARGO_HANDLERS; ++j) {
					weight_cnt_cargo += CargoHandlers[j]._weightCount[i];
				}
				Printf1("From cargo handlers: Baggage weight of airline %d = %d\n", 
				sizeof("From cargo handlers: Baggage weight of airline %d = %d\n"),
					concat2Num(i, weight_cnt_cargo));
			}

			Printf0("================================================\n", sizeof("================================================\n"));

			/* tell all Screening Officers to go home */
			Manager._allSODone = true;
			for (i = 0; i < NUM_SCREENING_OFFICERS; ++i) {
				Signal(OfficersLineLock, ScreeningOfficers[i]._commCV);
			}

			/* tell all Security Inspectors to go home */
			Manager._allSIDone = true;
			for (i = 0; i < NUM_SECURITY_INSPECTORS; ++i) {
				Signal(SecurityInspectors[i]._lock, SecurityInspectors[i]._commCV);
			}

			break;
		}


		/*
			Make sure Manager doesn't hog CPU
		*/
		for (i = 0; i < 20; ++i) {
			Yield();
		}
	}
	Exit(0);
}
Пример #9
0
VOID kill_linuxinput_task(struct linux_staticdata *lsd)
{
#warning This will not work since the task does not Wait() for this signal.
#warning Also we should wait for the child task to exit
    Signal(lsd->input_task, SIGBREAKF_CTRL_C);
}
Пример #10
0
void startScreeningOfficer() {
	#define mySO ScreeningOfficers[_myIndex]
	int _myIndex;
	/* Claim my screening officer */
	Acquire(GlobalDataLock);
    _myIndex = NumActiveScreeningOfficers++;
    Release(GlobalDataLock);

    /* Get to work! */
	while (true) {
		int suspicionLevel = false;
		int shortestLineIndex = -1; /* impossible value */
		int i; /* iterator */
		Acquire(OfficersLineLock);
		if (queue_empty(&OfficersLine)) {
			mySO._state = ONBREAK;
/*Printf1("SO %d is going to sleep\n", sizeof("SO %d is going to sleep\n"), _myIndex);*/
			/* Done? */
			if (Manager._allSODone) {
				Release(OfficersLineLock);
				break;
			}
			Wait(OfficersLineLock, mySO._commCV); /* Wait for a passenger */
			/* Done? */
			if (Manager._allSODone) {
				Release(OfficersLineLock);
				break;
			}
/*Printf1("SO %d is waking up\n", sizeof("SO %d is waking up\n"), _myIndex);*/
		}
		if (!queue_empty(&OfficersLine)) {
			Acquire(mySO._lock);
			mySO._state = BUSY;
			mySO._currentPassenger = queue_pop(&OfficersLine);
			Passengers[mySO._currentPassenger]._officerID = _myIndex;
			Signal(OfficersLineLock, OfficersLineCV); /* Wake up passenger */
			Release(OfficersLineLock);
			Wait(mySO._lock, mySO._commCV); /* Wait for passenger to approach */
			/* Generate PASS/FAIL Results */
			suspicionLevel = (17 * mySO._currentPassenger) % 10; /* PSUEDO rand() */
			SecurityFailResults[mySO._currentPassenger] = suspicionLevel > 8;
			if (SecurityFailResults[mySO._currentPassenger]) { /* FAIL */
				Printf1("Screening officer %d is suspicious of the hand luggage of passenger %d\n",
					sizeof("Screening officer %d is suspicious of the hand luggage of passenger %d\n"),
					concat2Num(_myIndex, mySO._currentPassenger));
			} else { /* PASS */
				Printf1("Screening officer %d is not suspicious of the hand luggage of passenger %d\n",
					sizeof("Screening officer %d is not suspicious of the hand luggage of passenger %d\n"),
					concat2Num(_myIndex, mySO._currentPassenger));
			}
			/* Find an Available Security Inspector */
			while (shortestLineIndex == -1) {
/*Printf1("SO %d is trying to find SI\n", sizeof("SO %d is trying to find SI\n"), _myIndex);*/
				#define inspector SecurityInspectors[i]
				Acquire(InspectorLineLock);	
/*Printf1("SO %d acquired InspectorLineLock\n", sizeof("SO %d acquired InspectorLineLock\n"), _myIndex);*/
				for (i = 0; i < NUM_SECURITY_INSPECTORS; ++i) {
					Acquire(inspector._lock);
/*Printf1("SO %d is checking SI %d\n", sizeof("SO %d is checking SI %d\n"), concat2Num(_myIndex, i));*/
					if (inspector._state == AVAIL && inspector._newPassenger == -1) {
						/* Found an inspector! */
						shortestLineIndex = inspector._id;
						inspector._newPassenger = mySO._currentPassenger;
						Release(inspector._lock);
						break;
					}
					Release(inspector._lock);
				}
				Release(InspectorLineLock);
				if (shortestLineIndex == -1) {
Printf1("SO %d is about to Yield\n", sizeof("SO %d is about to Yield\n"), _myIndex);
					Yield();
				}
				#undef inspector
/*				Wait(mySO._lock, mySO._commCV);*/
			}
			/* Found an inspetor for the passenger */
			Passengers[mySO._currentPassenger]._inspectorID = shortestLineIndex;
			Printf1("Screening officer %d directs passenger %d to security inspector %d\n",
				sizeof("Screening officer %d directs passenger %d to security inspector %d\n"),
				concat3Num(_myIndex, mySO._currentPassenger, shortestLineIndex));
			Signal(mySO._lock, mySO._commCV);
			Release(mySO._lock);
		} else {
			Release(OfficersLineLock);
		}
	}
	Exit(0);
}
Пример #11
0
void startSecurityInspector() {
	#define mySI SecurityInspectors[_myIndex]
	int _myIndex;
	/* Claim my security insepctor */
	Acquire(GlobalDataLock);
/*    _myIndex = NumActiveScreeningOfficers++;*/
	_myIndex = NumActiveSecurityInspectors++;
    Release(GlobalDataLock);

    /* Start work */
    while (true) {
    	bool suspicious, guilty;
    	Acquire(mySI._lock);
/*Printf1("SI %d has _newPassenger", sizeof("SI %d has _newPassneger"), _myIndex);
Printf1("%d\n", sizeof("%d\n"), mySI._newPassenger);*/
    	if (mySI._rtnPassSize == 0 && mySI._newPassenger == -1) {
    		mySI._state = AVAIL;
			/* Done? */
			if (Manager._allSIDone) {
				Release(mySI._lock);
				break;
			}
    		Wait(mySI._lock, mySI._commCV); /* Wait for Passenger to come */
			/* Done? */
			if (Manager._allSIDone) {
				Release(mySI._lock);
				break;
			}
    		mySI._state = BUSY;
    	}
    	if (mySI._rtnPassSize > 0) { /* priority to returning passengers */
    		while (mySI._rtnPassSize > 0) {
    			Signal(mySI._lock, mySI._rtnPassCV); /* Wake up passener */
    			Wait(mySI._lock, mySI._rtnPassCV); /* Wait on passenger */
    			Printf1("Security inspector %d permits returning passenger %d to board\n",
    				sizeof("Security inspector %d permits returning passenger %d to board\n"),
    				concat2Num(_myIndex, mySI._rtnPassenger));
    			mySI._passCount++;
/*    			mySI._rtnPassenger--;*/
				mySI._rtnPassSize--;
    			Signal(mySI._lock, mySI._rtnPassCV);
    		}
    		mySI._rtnPassenger = -1;
    	}
    	if (mySI._newPassenger != -1) { /* I have a new passenger to help */ 
    		suspicious = (mySI._newPassenger * 23) % 10 > 7; /* Psuedo Random */
    		guilty = suspicious || SecurityFailResults[mySI._newPassenger];
    		if (suspicious) {
    			Printf1("Security Inspector %d is suspicious of the hand luggage of passenger %d\n",
    				sizeof("Security Inspector %d is suspicious of the hand luggage of passenger %d\n"),
    				concat2Num(_myIndex, mySI._newPassenger));
    		} else {
    			Printf1("Security Inspector %d is not suspicious of the hand luggage of passenger %d\n",
    				sizeof("Security Inspector %d is not suspicious of the hand luggage of passenger %d\n"),
    				concat2Num(_myIndex, mySI._newPassenger));
    		}
    		if (guilty) {
				Passengers[mySI._newPassenger]._furtherQuestioning = true;
    			Printf1("Security inspector %d asks passenger %d to go for further examination\n", 
    				sizeof("Security inspector %d asks passenger %d to go for further examination\n"),
    				concat2Num(_myIndex, mySI._newPassenger));
    		} else {
    			Printf1("Security inspector %d allows passenger %d to board \n",
    				sizeof("Security inspector %d allows passenger %d to board \n"),
    				concat2Num(_myIndex, mySI._newPassenger));
    			mySI._passCount++;
    		}
    		mySI._newPassenger = -1;
    		Signal(mySI._lock, mySI._newPassCV);
    	}
    	Release(mySI._lock);
    }
    #undef mySI
	Exit(0);
}
Пример #12
0
void startCheckInStaff() {
#define myAirline Airlines[_myAirline]
#define my myAirline._cis[_myIndex]
#define passenger Passengers[my._currentPassenger]
	/* Claim my CIS */
	int _myAirline;
	int _myIndex; /* ID for currentThread */
    Acquire(GlobalDataLock);
	_myIndex = NumActiveCIS % NUM_CIS_PER_AIRLINE;
	_myAirline = NumActiveCIS / NUM_CIS_PER_AIRLINE;
    NumActiveCIS++;
    Release(GlobalDataLock);

    while (true) {
		/* Check lines */
		Acquire(myAirline._lock);
		if (my._lineSize == 0 && queue_empty(&myAirline._execQueue)) {
			/*Printf0("1\n", sizeof("1\n"));*/
			my._state = ONBREAK;
			/* 'Clock Out' for Break */
			myAirline._numOnBreakCIS++;
/*Printf1("Cis %d going to sleep\n", sizeof("Cis %d going to sleep\n"), _myIndex);*/
			Wait(myAirline._lock, my._commCV); /* Wait on Manager */ /* TODO - make sure okay to wait on aiport lock... maybe better? */
/*Printf1("Cis %d woke up by manager\n", sizeof("Cis %d woke up by manager\n"), _myIndex);*/
			/* Time to go home! TGIF! */
			if (my._done) {
				Printf1("Airline check-in staff %d of airline %d is closing the counter\n",
					sizeof("Airline check-in staff %d of airline %d is closing the counter\n"),
					concat2Num(_myIndex, _myAirline));
/*				Acquire(my._lock);*/
				Release(myAirline._lock);
/*				Wait(my._lock, my._commCV); *//* Wait forever, basically */
/*				Release(my._lock); *//* Never reaches here, but whatever... */
				break;
			}
			myAirline._numOnBreakCIS--;
		}
		/* Start helping a passenger */
		my._state = BUSY;
		Acquire(myAirline._cisLineLock);
		Acquire(myAirline._execLineLock);
		if (queue_size(&myAirline._execQueue) > 0) {
			my._currentPassenger = queue_pop(&myAirline._execQueue);
			passenger._cisID = _myIndex;
			Printf1("Airline check-in staff %d of airline %d serves an executive class passenger and economy line length = %d\n",
				sizeof("Airline check-in staff %d of airline %d serves an executive class passenger and economy line length = %d\n"),
				concat3Num(_myIndex, _myAirline, my._lineSize));
			Signal(myAirline._execLineLock, myAirline._execLineCV); /* Signal Passenger */
		} else if (my._lineSize > 0) {
			Printf1("Airline check-in staff %d of airline %d serves an economy class passenger and executive class line length = %d\n",
				sizeof("Airline check-in staff %d of airline %d serves an economy class passenger and executive class line length = %d\n"),
				concat3Num(_myIndex, _myAirline, queue_size(&myAirline._execQueue)));
			Signal(myAirline._cisLineLock, my._lineCV);
/*Printf1("Cis %d of airline %d wakes up passenger\n", sizeof("Cis %d of airline %d wakes up passenger\n"), _myIndex*1000+_myAirline);*/
		}
		/* Interact with Passenger */
		Acquire(my._lock);
		Release(myAirline._cisLineLock);
		Release(myAirline._execLineLock);
		Release(myAirline._lock);
		if (my._lineSize > 0 || my._currentPassenger != -1) {
/*Printf1("Cis %d of airline %d goes to sleep\n", sizeof("Cis %d of airline %d goes to sleep\n"), _myIndex*1000+_myAirline);*/
			Wait(my._lock, my._commCV); 
		} /* Otherwise, Manager woke you up for no reason */
		if (my._currentPassenger != -1) {
			int i;
			/* Assign seat number */
			Acquire(myAirline._lock);
			passenger._ticket._seat = myAirline._numCheckedinPassengers;
			myAirline._numCheckedinPassengers++;
			Release(myAirline._lock);
			/* Deal with baggage */
			Acquire(ConveyorLock);
			for (i = 0; i < passenger._numBaggages; ++i) {
				/*Printf0("3\n", sizeof("1\n"));*/
/*				#define bIndex (passenger._id * 3) + i
				#define bag Baggages[bIndex]*/
				#define bag Baggages[(passenger._id*3)+i]
				bag._airline = _myAirline; /* Tag the bag */
/*				queue_insert(&ConveyorBelt, bIndex);*/
				queue_insert(&ConveyorBelt, passenger._id*3+i);
				Printf1("Airline check-in staff %d of airline %d dropped bags to the conveyor system \n",
					sizeof("Airline check-in staff %d of airline %d dropped bags to the conveyor system \n"),
					concat2Num(_myIndex, _myAirline));
/*				myAirline._numExpectedBaggages++;*/
				my._weightCount += bag._weight;
				#undef bag
/*				#undef bIndex*/
			}
			Release(ConveyorLock);
			/* Direct Passenger to Airline */
			if (passenger._ticket._executive) {
				Printf2("Airline check-in staff %d of airline %d informs executive class passenger %d to board at gate %d\n",
					sizeof("Airline check-in staff %d of airline %d informs executive class passenger %d to board at gate %d\n"),
/*					concat3Num(_myAirline, my._currentPassenger, _myAirline), _myIndex);*/
					concat3Num(_myIndex, _myAirline, my._currentPassenger), _myAirline);
			} else {
				Printf2("Airline check-in staff %d of airline %d informs economy class passenger %d to board at gate %d\n",
					sizeof("Airline check-in staff %d of airline %d informs economy class passenger %d to board at gate %d\n"),
/*					concat3Num(_myAirline, my._currentPassenger, _myAirline), _myIndex);*/
					concat3Num(_myIndex, _myAirline, my._currentPassenger), _myAirline);
			}
			Signal(my._lock, my._commCV); 
			Wait(my._lock, my._commCV); 
		}
		my._currentPassenger = -1;
		Release(my._lock);
	} /* end while */
	Exit(0);
#undef passenger
#undef my
#undef myAirline
}
Пример #13
0
/*
	Start Functions - functions called by Fork() syscall.
*/
void startPassenger() {    
#define my Passengers[_myIndex]
#define liaison Liaisons[my._liaisonID]
	/* Claim my Passenger */
	int i, j; /* for-loop iterators */
	int _myIndex; /* ID for currentThread */
	int _minLineSize;

    Acquire(GlobalDataLock);
    _myIndex = NumActivePassengers++;
    Release(GlobalDataLock);

    /*
		Liaison Interaction
    */
	Acquire(LiaisonLineLock);
	_minLineSize = Liaisons[0]._lineSize;
	/* Find shortest line */
	for (i = 1; i < NUM_LIASONS; i++) {
		if (Liaisons[i]._lineSize < _minLineSize) {
			_minLineSize = Liaisons[i]._lineSize;
			my._liaisonID = i;
		}
	}

	Printf1("Passenger %d chose Liaison %d with a line length %d\n", 
		sizeof("Passenger %d chose Liaison %d with a line length %d\n"), 
		concat3Num(_myIndex, my._liaisonID, liaison._lineSize));
	/* Get in line? */
	if (liaison._state == BUSY) {
/*		Printf0("Passenger says liaison is BUSY\n", 
			sizeof("Passenger says liaison is BUSY\n"));
		Printf1("Passenger's liaison id: %d\n", 
			sizeof("Passenger's liaison id: %d\n"),
			_myIndex);*/
		liaison._lineSize++;
		Wait(LiaisonLineLock, liaison._lineCV);
		liaison._lineSize--;
	}
	Printf1("Passenger %d is moving along...\n", sizeof("Passenger %d is moving along...\n"), _myIndex);
	/* Go to Liaison */
	Acquire(liaison._lock);
	Release(LiaisonLineLock);
	/* Give Liaison my Passenger info */
	liaison._passCount[my._ticket._airline]++;
	liaison._bagCount[my._ticket._airline] += my._numBaggages;
	liaison._currentPassenger = _myIndex;
	Signal(liaison._lock, liaison._commCV); /* Signal Liaison */
	Wait(liaison._lock, liaison._commCV); /* Wait for Liaison */
	Printf1("Passenger %d of Airline %d is directed to the check-in counter\n", 
		sizeof("Passenger %d of Airline %d is directed to the check-in counter\n"),
		concat2Num(_myIndex, my._ticket._airline));
	Signal(liaison._lock, liaison._commCV);
	Release(liaison._lock);
#undef liaison
	/* end Liaison Interaction */

	/*
		Check-in Staff Interaction
	*/
#define myAirline Airlines[my._ticket._airline]
#define myCIS myAirline._cis[my._cisID]
	if (my._ticket._executive) {
		Acquire(myAirline._execLineLock);
		queue_insert(&myAirline._execQueue, _myIndex);
		Printf1("Passenger %d of Airline %d is waiting in the executive class line\n", 
			sizeof("Passenger %d of Airline %d is waiting in the executive class line\n"),
			concat2Num(_myIndex, my._ticket._airline));
/*		Wait(myAirline._execLineLock, myAirline._execLineLock); *//* Wait on CIS */
		Wait(myAirline._execLineLock, myAirline._execLineCV); /* Wait on CIS */
	} else { /* Economy */
		Acquire(myAirline._cisLineLock);
		/* Find shortest line */
		_minLineSize = myAirline._cis[0]._lineSize; /* declare at top of startPassenger */
		my._cisID = 0;
		for (i = 0; i < NUM_CIS_PER_AIRLINE; ++i) {
			if (myAirline._cis[i]._lineSize < _minLineSize) {
				_minLineSize = myAirline._cis[i]._lineSize;
				my._cisID = i;
			}
		}
		Printf2("Passenger %d of Airline %d chose Airline Check-In staff %d with a line length %d\n", 
			sizeof("Passenger %d of Airline %d chose Airline Check-In staff %d with a line length %d\n"),
			concat3Num(_myIndex, my._ticket._airline, my._cisID), _minLineSize);
			myCIS._lineSize++;
/*Printf1("Passenger %d of Airline %d is going to sleep and should be woken up by cis %d\n", sizeof("Passenger %d of Airline %d is going to sleep and should be woken up by cis %d\n"), concat3Num(_myIndex, my._ticket._airline, my._cisID));*/
		Wait(myAirline._cisLineLock, myCIS._lineCV);
/*Printf1("Passenger %d of Airline %d is woken up by cis %d\n", sizeof("Passenger %d of Airline %d is woken up by cis %d\n"), concat3Num(_myIndex, my._ticket._airline, my._cisID));*/
	}
	Acquire(myCIS._lock);
	if (my._ticket._executive) {
		Release(myAirline._execLineLock);
	} else {
		myCIS._lineSize--;
		Release(myAirline._cisLineLock);
	}
	/* Give baggage to CIS */
	myCIS._passCount++;
	myCIS._bagCount += my._numBaggages;
	myCIS._currentPassenger = _myIndex;
	Signal(myCIS._lock, myCIS._commCV); /* Signal CIS */
	Wait(myCIS._lock, myCIS._commCV); /* Wait on CIS */
	Printf1("Passenger %d of Airline %d was informed to board at gate %d\n",
		sizeof("Passenger %d of Airline %d was informed to board at gate %d\n"),
		concat3Num(_myIndex, my._ticket._airline, my._ticket._airline));
	Signal(myCIS._lock, myCIS._commCV); /* Signal CIS */
	Release(myCIS._lock);

#undef myCIS
#undef myAirline
	/* end Check-in Staff Interaction */

	/*
		Screening Officer Interaction
	*/
	Acquire(OfficersLineLock);
	queue_insert(&OfficersLine, _myIndex);
	Wait(OfficersLineLock, OfficersLineCV);
	Printf1("Passenger %d gives the hand-luggage to screening officer %d\n",
		sizeof("Passenger %d gives the hand-luggage to screening officer %d\n"),
		concat2Num(_myIndex, my._officerID));
	Acquire(ScreeningOfficers[my._officerID]._lock);
	Release(OfficersLineLock);
	Signal(ScreeningOfficers[my._officerID]._lock, ScreeningOfficers[my._officerID]._commCV);
	Wait(ScreeningOfficers[my._officerID]._lock, ScreeningOfficers[my._officerID]._commCV);
	/* officer lock is released below! */
	/* end Screening Officer Interaction */

	/*
		Security Inspector Interaction
	*/
	#define inspector SecurityInspectors[my._inspectorID]
	Printf1("Passenger %d moves to security inspector %d\n",
		sizeof("Passenger %d moves to security inspector %d\n"),
		concat2Num(_myIndex, my._inspectorID));
	Acquire(inspector._lock);
	Release(ScreeningOfficers[my._officerID]._lock);
	inspector._newPassenger = _myIndex;
	if (inspector._state == AVAIL) { /* Wake up inspector */
		Signal(inspector._lock, inspector._commCV);
	}
	Wait(inspector._lock, inspector._newPassCV); /* Wait for security results */
	if (my._furtherQuestioning) {
		Printf1("Passenger %d goes for futher questioning\n", 
			sizeof("Passenger %d goes for futher questioning\n"),
			_myIndex);
		Release(inspector._lock);
		for (i = 0; i < 10; ++i) {
			Yield(); /* Simulate Further questioning */
		}
		Printf1("Passenger %d comes back to security inspector %d after further examination\n",
			sizeof("Passenger %d comes back to security inspector %d after further examination\n"),
			concat2Num(_myIndex, my._inspectorID));
		Acquire(inspector._lock);
/*		inspector._rtnPassenger++;*/
		inspector._rtnPassSize++;
		if (inspector._state == AVAIL) {
			Signal(inspector._lock, inspector._commCV);
		}
/*Printf0("About to wait\n", sizeof("About to wait\n"));*/
		Wait(inspector._lock, inspector._rtnPassCV);
/*Printf0("Woken up\n", sizeof("Woken up\n"));*/
		inspector._rtnPassenger = _myIndex;
		Signal(inspector._lock, inspector._rtnPassCV);
		Wait(inspector._lock, inspector._rtnPassCV);
	}	
	Release(inspector._lock);

	#undef inspector
	/* end Security Inspector Interaction */

	/*
		Reached the Boarding Lounge
	*/
	#define myAirline Airlines[my._ticket._airline]

	Acquire(myAirline._lock);
	myAirline._numReadyPassengers++;
	Printf1("Passenger %d of Airline %d reached the gate %d\n",
		sizeof("Passenger %d of Airline %d reached the gate %d\n"),
		concat3Num(_myIndex, my._ticket._airline, my._ticket._airline));
	Wait(myAirline._lock, myAirline._boardLoungeCV); /* Wait for boarding call by manager */
	Printf1("Passenger %d of Airline %d boarded airline %d\n",
		sizeof("Passenger %d of Airline %d boarded airline %d\n"),
		concat3Num(_myIndex, my._ticket._airline, my._ticket._airline));
	Release(myAirline._lock);

	#undef myAirline
	/* End Boarding Lounge */

	Exit(0);
#undef my
}
Пример #14
0
/*}}}*/
static void controller_routine(char *arg)
{ int		 number_workers;
  int		 first_channel;
  int		 i;
  char		*buf;
  int		*wbuf;
  int		 endtime;
  int		 size;
  int		 checksum;
  int		 worker;
  FullStats	 stats;

#define to_worker(i)   (first_channel + i + i + 1)
#define from_worker(i) (first_channel + i + i)

/*{{{  initialise */
  if (sscanf(arg, "%d.%d", &number_workers, &first_channel) != 2)
   Fatal("controller routine, invalid argument %s", arg);

  logname = getenv("HWTEST_LOGFILE");
  if (logname == NULL)
   logname = "/helios/local/tests/hwtest/hwtest.log";

  buf = malloc(MaxCommsTransfer);
  if (buf == NULL)
   Fatal("controller routine, out of memory.");
  wbuf = (int *) buf;

  for (worker = 0; worker < number_workers; worker++)
   { if (write(to_worker(worker), buf, sizeof(int)) != sizeof(int))
      Fatal("controller routine, failed to send initial data to worker %d", worker);
     if (full_read(from_worker(worker), buf, sizeof(int)) != sizeof(int))
      Fatal("controller routine, failed to receive initial data from worker %d", worker);
   }

	/* The main memory tester can now allocate its buffers.		*/
  Signal(&ThreadsReady);

  endtime  = ((((24 * Days) + Hours) * 60) + Minutes) * 60;
  endtime += time(NULL);
/*}}}*/
/*{{{  communication with workers */
  while (endtime > time(NULL))
   { 
     if (!ExtraComms)
      { Delay(5 * OneSec); continue; }

     for (size = 32; size <= MaxCommsTransfer; size *= 2)
      {		/* initialise the buffer with random data.		*/
	wbuf[0] = 0;	/* checksum */
	for (i = 1; i < (size / sizeof(int)); i++)
	 { wbuf[i] = hw_rand();
	   wbuf[0] += wbuf[i];
         }

	for (worker = 0; worker < number_workers; worker++)
	 { if (write(to_worker(worker), (char *) &size, sizeof(int)) != sizeof(int))
	   	Fatal("controller routine failed to send size %d to worker %d", size, worker);
	   if (write(to_worker(worker), buf, size) != size)
	   	Fatal("controller routine failed to write block of %d bytes to worker %d", size, worker);
	   if (full_read(from_worker(worker), buf, size) != size)
		Fatal("controller routine, failed to read back buffer of %d bytes from worker %d", size, worker);
	   for (i = 1, checksum = 0; i < (size / sizeof(int)); i++)
	    checksum += wbuf[i];
	   if (checksum != wbuf[0])
	    { Report("controller routine, corruption in buffer of %d bytes read back from worker %d",
	 		size, worker);
	      wbuf[0] = checksum;
	    }
         }	/* for all the workers		*/

        if (endtime < time(NULL))
	  break;
      }		/* sizes loop			*/
   }		/* while (endtime > time())	*/
/*}}}*/
/*{{{  terminating the workers */
	/* At this point the runtime has expired and it is necessary	*/
	/* to send a terminate message to all the workers. Also the	*/
	/* Finished flag should be set so that the testing going on	*/
	/* within the controller will stop.				*/
  Finished = TRUE;
  size     = 0;
  for (worker = 0; worker < number_workers; worker++)
   if (write(to_worker(worker), (char *) &size, sizeof(int)) != sizeof(int))
    Fatal("controller routine, failed to send terminate request to worker %d", worker);
/*}}}*/
/*{{{  collecting the stats */
	/* Now collect together the results from all the workers.	*/
  TotalStats.OffchipMemoryG	=
  TotalStats.OffchipMemoryM	=
  TotalStats.OffchipMemoryK	=
  TotalStats.OffchipFailures	=
  TotalStats.OnchipMemoryG	=
  TotalStats.OnchipMemoryM	=
  TotalStats.OnchipMemoryK	=
  TotalStats.OnchipFailures	=
  TotalStats.LinkG		=
  TotalStats.LinkM		=
  TotalStats.LinkK		=
  TotalStats.LinkFailures	= 0;

  for (worker = 0; worker < number_workers; worker++)
   { 
     if (full_read(from_worker(worker), (char *) &stats, sizeof(FullStats)) != sizeof(FullStats))
      Fatal("controller routine, failed to collect results from worker %d", worker);

     if (Verbose)
      display_results(&stats);
      
     TotalStats.OffchipMemoryK	+= stats.OffchipMemory;
     TotalStats.OffchipFailures	+= stats.OffchipFailures;
     TotalStats.OnchipMemoryK	+= stats.OnchipMemory;
     TotalStats.OnchipFailures	+= stats.OnchipFailures;
     for (i = 0; i < stats.NumberLinks; i++)
      { TotalStats.LinkK	+= stats.LinkStats[i].ReadIterations;
	TotalStats.LinkFailures	+= stats.LinkStats[i].ReadFailures;
      }
   }

	/* Include the results from the test routines running	*/
	/* within this worker.					*/
  for (i = 1; i < NumberThreads; i++)
   Wait(&ResultsReady);

  TotalStats.OffchipMemoryK	+= Results.OffchipMemory;
  TotalStats.OffchipFailures	+= Results.OffchipFailures;
  TotalStats.OnchipMemoryK	+= Results.OnchipMemory;
  TotalStats.OnchipFailures	+= Results.OnchipFailures;
  for (i = 0; i < Results.NumberLinks; i++)
   { TotalStats.LinkK		+= stats.LinkStats[i].ReadIterations;
     TotalStats.LinkFailures	+= stats.LinkStats[i].ReadFailures;
   }
/*}}}*/
/*{{{  calculate the real stats */
	/* The stats structure now contains the total amount of memory	*/
	/* that has been checked, plus the total number of link		*/
	/* iterations. This has to be converted to KByte hours etc,	*/
	/* taking some care to avoid overflow. Running on very large	*/
	/* networks with 256 4Mbyte processors for a whole week should	*/
	/* still be OK - just.						*/
	/*  1) divide by 60 to give a minutes rating.			*/
  TotalStats.OffchipMemoryK	/= 60;
  TotalStats.OnchipMemoryK	/= 60;
	/*  2) now multiply by the number of minutes in the run		*/
  TotalStats.OffchipMemoryK	*= ((((Days * 24) + Hours) * 60) + Minutes);
  TotalStats.OnchipMemoryK	*= ((((Days * 24) + Hours) * 60) + Minutes);
	/*  3) on-chip sizes were in bytes, not K			*/
  TotalStats.OnchipMemoryK	/= 1024;
	/*  4) update G and M values					*/
  TotalStats.OffchipMemoryM	 = TotalStats.OffchipMemoryK / 1024;
  TotalStats.OffchipMemoryK	 = TotalStats.OffchipMemoryK % 1024;
  TotalStats.OffchipMemoryG	 = TotalStats.OffchipMemoryM / 1024;
  TotalStats.OffchipMemoryM	 = TotalStats.OffchipMemoryM % 1024;
  TotalStats.OnchipMemoryM	 = TotalStats.OnchipMemoryK / 1024;
  TotalStats.OnchipMemoryK	 = TotalStats.OnchipMemoryK % 1024;
  TotalStats.OnchipMemoryG	 = TotalStats.OnchipMemoryM / 1024;
  TotalStats.OnchipMemoryM	 = TotalStats.OnchipMemoryM % 1024;
	/*  5) update link stats in much the same way			*/
  TotalStats.LinkK		/= 32;
  TotalStats.LinkK		*= DataPerIteration;
  TotalStats.LinkK		/= 32;	/* 32 * 32 == 1K */
  TotalStats.LinkM		 = TotalStats.LinkK / 1024;
  TotalStats.LinkK		 = TotalStats.LinkK % 1024;
  TotalStats.LinkG		 = TotalStats.LinkM / 1024;
  TotalStats.LinkM		 = TotalStats.LinkM % 1024;

  if (Verbose)
   { printf("Summary for this run.\n\n");
     printf(str4, TotalStats.OffchipMemoryG, TotalStats.OffchipMemoryM,
		  TotalStats.OffchipMemoryK, TotalStats.OffchipFailures);
     printf(str5, TotalStats.OnchipMemoryG, TotalStats.OnchipMemoryM,
		  TotalStats.OnchipMemoryK, TotalStats.OnchipFailures);
     printf(str6, TotalStats.LinkG, TotalStats.LinkM,
		  TotalStats.LinkK, TotalStats.LinkFailures);
     puts("\n");
   }
/*}}}*/
/*{{{  update the log file info */
  readin_logfile();	/* automatically created if necessary	*/

  LogStats.OffchipMemoryG	+= TotalStats.OffchipMemoryG;
  LogStats.OffchipMemoryM	+= TotalStats.OffchipMemoryM;
  LogStats.OffchipMemoryK	+= TotalStats.OffchipMemoryK;
  LogStats.OnchipMemoryG	+= TotalStats.OnchipMemoryG;
  LogStats.OnchipMemoryM	+= TotalStats.OnchipMemoryM;
  LogStats.OnchipMemoryK	+= TotalStats.OnchipMemoryK;
  LogStats.OffchipFailures	+= TotalStats.OffchipFailures;
  LogStats.OnchipFailures	+= TotalStats.OnchipFailures;
  LogStats.LinkG		+= TotalStats.LinkG;
  LogStats.LinkM		+= TotalStats.LinkM;
  LogStats.LinkK		+= TotalStats.LinkK;
  LogStats.LinkFailures		+= TotalStats.LinkFailures;

	/* And adjust these results as appropriate		*/
  LogStats.OffchipMemoryM	+= LogStats.OffchipMemoryK / 1024;
  LogStats.OffchipMemoryK	%= 1024;
  LogStats.OffchipMemoryG	+= LogStats.OffchipMemoryM / 1024;
  LogStats.OffchipMemoryM	%= 1024;
  LogStats.OnchipMemoryM	+= LogStats.OnchipMemoryK / 1024;
  LogStats.OnchipMemoryK	%= 1024;
  LogStats.OnchipMemoryG	+= LogStats.OnchipMemoryM / 1024;
  LogStats.OnchipMemoryM	%= 1024;
  LogStats.LinkM		+= LogStats.LinkK / 1024;
  LogStats.LinkK		%= 1024;
  LogStats.LinkG		+= LogStats.LinkM / 1024;
  LogStats.LinkM		%= 1024;
  NumberHours			+= ((24 * Days) + Hours);

  writeout_logfile();
/*}}}*/
}
Пример #15
0
/* Run the given command line as if with exec. What we actually do is fork the
   command line as a subprocess, then loop, relaying data between the socket and
   the subprocess. This allows Ncat to handle SSL from the socket and give plain
   text to the subprocess, and also allows things like logging and line delays.
   Never returns. */
void netexec(struct fdinfo *info, char *cmdexec)
{
    int child_stdin[2];
    int child_stdout[2];
    int pid;
    int crlf_state;

    char buf[DEFAULT_TCP_BUF_LEN];
    int maxfd;

    if (o.debug) {
        switch (o.execmode) {
        case EXEC_SHELL:
            logdebug("Executing with shell: %s\n", cmdexec);
            break;
#ifdef HAVE_LUA
        case EXEC_LUA:
            logdebug("Executing as lua script: %s\n", cmdexec);
            break;
#endif
        default:
            logdebug("Executing: %s\n", cmdexec);
            break;
        }
    }

    if (pipe(child_stdin) == -1 || pipe(child_stdout) == -1)
        bye("Can't create child pipes: %s", strerror(errno));

    pid = fork();
    if (pid == -1)
        bye("Error in fork: %s", strerror(errno));
    if (pid == 0) {
        /* This is the child process. Exec the command. */
        close(child_stdin[1]);
        close(child_stdout[0]);

        /* We might have turned off SIGPIPE handling in ncat_listen.c. Since
           the child process SIGPIPE might mean that the connection got broken,
           ignoring it could result in an infinite loop if the code here
           ignores the error codes of read()/write() calls. So, just in case,
           let's restore SIGPIPE so that writing to a broken pipe results in
           killing the child process. */
        Signal(SIGPIPE, SIG_DFL);

        /* rearrange stdin and stdout */
        Dup2(child_stdin[0], STDIN_FILENO);
        Dup2(child_stdout[1], STDOUT_FILENO);

        setup_environment(info);

        switch (o.execmode) {
        char **cmdargs;

        case EXEC_SHELL:
            execl("/bin/sh", "sh", "-c", cmdexec, (void *) NULL);
            break;
#ifdef HAVE_LUA
        case EXEC_LUA:
            lua_run();
            break;
#endif
        default:
            cmdargs = cmdline_split(cmdexec);
            execv(cmdargs[0], cmdargs);
            break;
        }

        /* exec failed. */
        die("exec");
    }

    close(child_stdin[0]);
    close(child_stdout[1]);

    maxfd = child_stdout[0];
    if (info->fd > maxfd)
        maxfd = info->fd;

    /* This is the parent process. Enter a "caretaker" loop that reads from the
       socket and writes to the subprocess, and reads from the subprocess and
       writes to the socket. We exit the loop on any read error (or EOF). On a
       write error we just close the opposite side of the conversation. */
    crlf_state = 0;
    for (;;) {
        fd_set fds;
        int r, n_r;

        FD_ZERO(&fds);
        FD_SET(info->fd, &fds);
        FD_SET(child_stdout[0], &fds);

        r = fselect(maxfd + 1, &fds, NULL, NULL, NULL);
        if (r == -1) {
            if (errno == EINTR)
                continue;
            else
                break;
        }
        if (FD_ISSET(info->fd, &fds)) {
            int pending;

            do {
                n_r = ncat_recv(info, buf, sizeof(buf), &pending);
                if (n_r <= 0)
                    goto loop_end;
                write_loop(child_stdin[1], buf, n_r);
            } while (pending);
        }
        if (FD_ISSET(child_stdout[0], &fds)) {
            char *crlf = NULL, *wbuf;
            n_r = read(child_stdout[0], buf, sizeof(buf));
            if (n_r <= 0)
                break;
            wbuf = buf;
            if (o.crlf) {
                if (fix_line_endings((char *) buf, &n_r, &crlf, &crlf_state))
                    wbuf = crlf;
            }
            ncat_send(info, wbuf, n_r);
            if (crlf != NULL)
                free(crlf);
        }
    }
loop_end:

#ifdef HAVE_OPENSSL
    if (info->ssl != NULL) {
        SSL_shutdown(info->ssl);
        SSL_free(info->ssl);
    }
#endif
    close(info->fd);

    exit(0);
}
Пример #16
0
static VOID inputtask_entry(struct inputtask_params *inputparams)
{
    struct linux_staticdata *lsd;
    struct inputtask_params itp;
    UBYTE lastcode = 0xFF;
    
    struct MsgPort *kbd_port = NULL;
    struct MsgPort *mouse_port = NULL;
    
    struct mouse_state oldstate = { { 0, 0, 0 }, 0, 0 };
    struct pHidd_Mouse_Event mouse_event;
    
    HIDD *unixio = NULL;
    ULONG kbdsig, mousesig, sigs;
    /* We must copy the parameter struct because they are allocated
     on the parent's stack */
kprintf("INSIDE INPUT TASK\n");
    itp = *inputparams;
    lsd = itp.lsd;
kprintf("in inputtask: lsd = %p\n", lsd);

kprintf("CREATING UNIXIO,,, OOPBase=%p\n", OOPBase);
kprintf("now\n");
    unixio = (HIDD)New_UnixIO(OOPBase, SysBase);
kprintf("UNIXIO %p\n", unixio);
    if (NULL == unixio) {
    	goto failexit;
    }
    
    kbd_port   = CreateMsgPort();
    mouse_port = CreateMsgPort();
    
    if (NULL == kbd_port || NULL == mouse_port)
	goto failexit;
    
    Signal(itp.parent, itp.ok_signal);
    
    kbdsig	= 1L << kbd_port->mp_SigBit;
    mousesig	= 1L << mouse_port->mp_SigBit;
kprintf("SIGS: %p, %p\n", kbdsig, mousesig);
kprintf("FDS: %d, %d\n", lsd->kbdfd, lsd->mousefd);

    Hidd_UnixIO_AsyncIO(unixio, lsd->kbdfd,   vHidd_UnixIO_Terminal, kbd_port,	vHidd_UnixIO_Read, SysBase);
    Hidd_UnixIO_AsyncIO(unixio, lsd->mousefd, vHidd_UnixIO_Terminal, mouse_port,  vHidd_UnixIO_Read, SysBase);
    
    for (;;) {
	LONG err_kbd, err_mouse;
	
	//kprintf("GETTING INPUT FROM UNIXIO\n");
	/* Turn on kbd support */
//	init_kbd(lsd);
	
	
//    	ret = (int)Hidd_UnixIO_Wait( unixio, lsd->kbdfd, vHidd_UnixIO_Read, NULL, NULL);
//	cleanup_kbd(lsd);
//	kprintf("GOT INPUT FROM UNIXIO\n");
	
	sigs = Wait( kbdsig | mousesig );

	if (sigs & kbdsig) {
	
//kprintf("---------- GOT KBD INPUT --------------------\n");
 	    for (;;) {
		UBYTE code;
		size_t bytesread;
	    
	    
		bytesread = read(lsd->kbdfd, &code, 1);
		if (-1 == bytesread)  {
	    	    kprintf("!!! COULD NOT READ FROM LINUX KBD DEVICE: %s\n"
			, strerror(errno));
		    break;
		
		} else {
	    	    /* Let the kbd hidd handle it */
		    /* Key doewn ? */
		    
		    //kprintf("## code %d\n", code);
		    if (code == lastcode)
			break;
		    
	    	    // if (!(code & 0x80)) kprintf("GOT SCANCODE %d from kbd hidd\n", code);
		    if (code == 88) /* F12 */
		    {
			    kill(getpid(), SIGTERM);
		    }
		
		    /* Send code to the application */
    	    	    ObtainSemaphore(&lsd->sema);
		    if (lsd->kbdhidd) HIDD_LinuxKbd_HandleEvent(lsd->kbdhidd, code);
    	    	    ReleaseSemaphore(&lsd->sema);

		    lastcode = code;
		}
		break;

	    }	/* for (;;) */
	    free_unixio_message(kbd_port, lsd);

	    err_kbd = Hidd_UnixIO_AsyncIO(unixio, lsd->kbdfd,   vHidd_UnixIO_Terminal, kbd_port,	vHidd_UnixIO_Read, SysBase);

	} /* if (sigs & kbdsig) */
	
	if (sigs & mousesig)
	{
	    ULONG i;
	    LONG bytesread;
	    UBYTE buf[4];
	    BYTE dx = 0, dy = 0;
	    struct mouse_state newstate;
	    
	    /* Got mouse event */
	    //kprintf("------------- MOUSE EVENT ------------\n");
	    for (i = 0; i < 4; i ++) {
	    	bytesread = read(lsd->mousefd, &buf[i], 1);
		if (-1 == bytesread)
		{
		    if (errno == EAGAIN)
		    {
		    	i--;
			continue;
		    }
		    kprintf("!!! linux input task: Could not read from mouse device: %s\n", strerror(errno));
		    goto end_mouse_event;    
		}
		
		if ((buf[0] & 8) != 8) i--;
	    }
	    
	    //kprintf("%02x: %02x: %02x\n", buf[0], buf[1], buf[2]);
	    /* Get button states */
	    newstate.buts[0] = (buf[0] & 0x01) ? 1 : 0;
	    newstate.buts[1] = (buf[0] & 0x02) ? 1 : 0;
	    newstate.buts[2] = (buf[0] & 0x04) ? 1 : 0;
	    
	    if (buf[1] != 0) {
		dx = (buf[0] & 0x10) ? buf[1] - 256 : buf[1];
	    }
	    
	    if (buf[2] != 0) {
		dy = (buf[0] & 0x20) ? buf[2] - 256 : buf[2];
	    }
		
	    newstate.dx = dx;
	    newstate.dy = -dy;
	    
	    //kprintf("EVENT: STATE 1:%d, 2:%d, 3:%d, dx:%d, dy:%d\n"
	    //	, newstate.buts[0], newstate.buts[1], newstate.buts[2]
	    //	, newstate.dx, newstate.dy);
		
            ObtainSemaphore(&lsd->sema);    
    	    if (lsd->mousehidd)
	    {
    		mouse_event.x = newstate.dx;
		mouse_event.y = newstate.dy;

		if (newstate.dx || newstate.dy)
		{
	    	    mouse_event.button = vHidd_Mouse_NoButton;
		    mouse_event.type = vHidd_Mouse_Motion;

	    	    HIDD_LinuxMouse_HandleEvent(lsd->mousehidd, &mouse_event);
		}

		if (newstate.buts[0] != oldstate.buts[0])
		{
	    	    mouse_event.button = vHidd_Mouse_Button1;
		    mouse_event.type = newstate.buts[0] ? vHidd_Mouse_Press : vHidd_Mouse_Release;	

	    	    HIDD_LinuxMouse_HandleEvent(lsd->mousehidd, &mouse_event);
		}

		if (newstate.buts[1] != oldstate.buts[1])
		{
	    	    mouse_event.button = vHidd_Mouse_Button2;
		    mouse_event.type = newstate.buts[1] ? vHidd_Mouse_Press : vHidd_Mouse_Release;	

	    	    HIDD_LinuxMouse_HandleEvent(lsd->mousehidd, &mouse_event);
		}

		if (newstate.buts[2] != oldstate.buts[2])
		{
	    	    mouse_event.button = vHidd_Mouse_Button3;
		    mouse_event.type = newstate.buts[2] ? vHidd_Mouse_Press : vHidd_Mouse_Release;	

	    	    HIDD_LinuxMouse_HandleEvent(lsd->mousehidd, &mouse_event);
		}
	    }
    	    ReleaseSemaphore(&lsd->sema);
	    
    	    oldstate = newstate;
	    	    	    
end_mouse_event:
	    free_unixio_message(mouse_port, lsd);

	    err_mouse	= Hidd_UnixIO_AsyncIO(unixio, lsd->mousefd, vHidd_UnixIO_Terminal, mouse_port,  vHidd_UnixIO_Read, SysBase);

	}
    	
    } /* Forever */
    
failexit:

    if (NULL != kbd_port)
    	DeleteMsgPort(kbd_port);

    if (NULL != mouse_port)
	DeleteMsgPort(mouse_port);
	
    if (NULL != unixio)
    	OOP_DisposeObject((OOP_Object *)unixio);

    Signal(itp.parent, itp.fail_signal);
     
    return;
    
}
Пример #17
0
void* request (void* data){
    pthread_detach(pthread_self());
	int serverfd=*(int*)data;
	int clientfd;
	char headerBuff[MAXHEADERSIZE];
    char RequestHeader[MAXHEADERSIZE];
	char hostname[MAXHOSTSIZE];
	char Buffer[MAXBUFFERSIZE];
    char* urlname; 
    char* cache_buff;
    int cache_size = 0;
	int error;
	int byte;
	int getbyte;
    int cachehit = 0;
	Signal(SIGPIPE,	SIG_IGN);
    free(data);
    rio_t serverrio_t;
//    Rio_readinitb(&serverrio_t,serverfd);
	/*set the structure, and set port to 80*/ 
	printf("to Start read %u\n",pthread_self());

	byte=Rio_readn(serverfd,headerBuff,sizeof(headerBuff));
//	byte=read(serverfd,headerBuff,sizeof(headerBuff));
	printf("finish read byte:%d  %u\n",byte,pthread_self());
	if(byte<=0){
		close(serverfd);
        pthread_exit(NULL);
	}
	printf("%s\n",headerBuff);
	fflush(stdout);

    /*Check if the webpage is cached. if cache hit, no need to connect to server*/
    if(takeurlname(headerBuff,&urlname) == 0){
        perror("Cannot find url name\n");
        close(serverfd);
        pthread_exit(NULL);
    }

	printf("Try to get cached data: %u\n",pthread_self());
    /* Try to get cached data, must check no thread writing the cache,
     * and use FILO architecture to lock when there threads reading cache*/
/*
    P(&mutex);
    readcnt++;
    if(readcnt == 1)
        P(&w);
    V(&mutex);
    if( Get_cachedata(urlname,serverfd) > 0){
        cachehit = 1;
    }

    P(&mutex);
    readcnt--;
    if(readcnt == 0)
        V(&w);
    V(&mutex);
    
    if(cachehit){
        close(serverfd);
        pthread_exit(NULL);
    }
*/
	printf("No cached data try connect: %u\n",pthread_self());
    /* Webpage not cached, retrieve information from web server */

	if( (clientfd=socket(AF_INET,SOCK_STREAM,0))<0){
		perror("socket");
        close(serverfd);
        pthread_exit(NULL);
	} 
//    Rio_readinitb(&clientrio_t,clientfd);


    /* Set the request to the server */ 
	if( settherequest(headerBuff,RequestHeader,hostname) == 0){
		perror("Set Request Error\n");
        close(serverfd);
        pthread_exit(NULL);
	}
	printf("%s\n",RequestHeader);
	fflush(stdout);
   
    /*get server's address info*/
	struct addrinfo *hostinfo;
	if( (error=getaddrinfo(hostname,"http",NULL,&hostinfo)) >0){
		perror("hostinfo");
        close(serverfd);
        pthread_exit(NULL);
	}
    /* connect to the server*/
	if( (connect(clientfd,hostinfo->ai_addr,hostinfo->ai_addrlen))<0){
		perror("connect");
        close(serverfd);
		return NULL;
	}
	printf("Ready to transmitt data: %u\n",pthread_self());
	/*pass the request from browser to server*/
	Rio_writen(clientfd,RequestHeader,byte);
	/*read the information from web server and send it to browser*/

   cache_buff = (char*) malloc(MAX_OBJECT_SIZE*sizeof(char));
    bzero(cache_buff,MAX_OBJECT_SIZE);
	while(1){
//		getbyte=read(clientfd,Buffer,sizeof(Buffer));
		getbyte=Rio_readn(clientfd,Buffer,sizeof(Buffer));
		if(getbyte<=0)
			break;
        if(cache_size + getbyte < MAX_OBJECT_SIZE){
            memcpy(cache_buff + cache_size,Buffer,getbyte);
        }
        cache_size += getbyte;
		Rio_writen(serverfd,Buffer,getbyte);
	}
	printf("Finish transmitt data: %u\n",pthread_self());
    /* if size fit in cache, write into cache, else free the content*/
/*    
    if(cache_size < MAX_OBJECT_SIZE){
        char* new_cache_buff = realloc(cache_buff,cache_size);
        free(cache_buff);
        if(new_cache_buff == NULL){
            perror("Realloc fail\n");
	        close(clientfd);
        	close(serverfd);
            pthread_exit(NULL);
        }

        P(&w);
        Create_cache(urlname,new_cache_buff,cache_size);
        Cache_checker();
        V(&w);
        
    }
    else{
        free(cache_buff);
    }
*/	printf("Finish cached data: %u\n",pthread_self());
	close(clientfd);
	close(serverfd);
    pthread_exit(NULL);
}
Пример #18
0
/*
##############################################
##Int ModuleResize(Int argc, Char *argv[])
##############################################
*/
Int ModuleResize(Int argc, Char *argv[])
{
	Uns                 initMask            = 0;
	Int                 status              = EXIT_SUCCESS;
	Rendezvous_Attrs    rzvAttrs            = Rendezvous_Attrs_DEFAULT;
	Fifo_Attrs          fAttrs              = Fifo_Attrs_DEFAULT;
	Rendezvous_Handle   hRendezvousInit     = NULL;
	Rendezvous_Handle   hRendezvousWriter   = NULL;
	Rendezvous_Handle   hRendezvousCleanup  = NULL;
	Int                 numThreads			= 0;
	pthread_t 			id_listen[5] 		= {0};
	Void               *ret;

	char 				devicebuf[16] 		= {0};

	CaptureEnv          captureEnv;
	WriterEnv           writerEnv;
	WriterEnv			writerLowRateEnv;
	DetectEnv			detectEnv;
	VideoEnv            videoEnv;
	VideoEnv            videoLowRateEnv;//dd
	VideoEnv            LowRateResize;
	AudioEnv            audioEnv;
	CtrlEnv             ctrlEnv;
	char box_version[64] = {0};
	OutputVideoInfo		outputhandle;
	textinfo			*texthandle;
	int 				DHCPVAL = 0, tmp = 0;
	char 				gateway[255] = {0};

	struct sched_param  schedParam;
	pthread_t           captureThread;
	pthread_t           detectThread;
	pthread_t           writerThread;
	pthread_t			writerLowThread;
	pthread_t           videoThread;
	pthread_t           audioThread;
	pthread_t			videoLowThread;
	pthread_t			resizeLowThread;
#ifdef DSS_ENC_1100_1200
	pthread_t           webListenThread;
#endif
	pthread_attr_t      attr;
	int       index = 0;
	int result = 0;
	char ts_version[128] = {0};
	/* Zero out the thread environments */
	Dmai_clear(captureEnv);
	Dmai_clear(writerEnv);
	Dmai_clear(videoEnv);
	Dmai_clear(audioEnv);
	Dmai_clear(ctrlEnv);

	mid_task_init();
	trace_init();
	open_gpio_port();

	ts_build_get_version(ts_version, sizeof(ts_version));

	strcpy(box_version, BOX_VER);
	strcat(box_version, CODE_TYPE);
	strcat(box_version, DEUBG);
	printf("[%s] Module Encode Program %s V%s\n", CODE_COND, BOARD_TYPE, box_version);
	printf("the build time is %s,the git vesion is %s.the ts version is %s\n\n", g_make_build_date, _VERSION, ts_version);

	initMutexPthread();
	InitgblCommonMutex();
	InitSysParams();
	initOutputVideoParam();
	InitHVTable(&gHVTable);
	//	webgetDHCPFlag(tmp, &DHCPVAL);
	//	readDHCPValue(DHCPCONFIG_FILE, &DHCPVAL);
	//	setDHCPFlag(DHCPVAL);
	gLogoinfo = initLogoMod();
	initTextinfo();

	ReadEncodeParamTable(CONFIG_NAME, &gSysParaT);
	DHCPVAL = gSysParaT.sysPara.nTemp[0];
	printf("----mic=%x:%x:%x:%x:%x:%x\n",gSysParaT.sysPara.szMacAddr[0],gSysParaT.sysPara.szMacAddr[1],gSysParaT.sysPara.szMacAddr[2],
			gSysParaT.sysPara.szMacAddr[3],gSysParaT.sysPara.szMacAddr[4],gSysParaT.sysPara.szMacAddr[5]);

	ReadLowbitParamTable(LOWBIT_PARAM, &gSysParaT);

	memset(&outputhandle, 0, sizeof(OutputVideoInfo));
	getOutputvideohandle(&outputhandle);

	readOutputVideoParam(VIDEOENCODE_FILE, &outputhandle);

	setOutputvideohandle(&outputhandle);
	//sleep(10);
	ReadLogoinfo(LOGOCONFIGNAME, gLogoinfo);
	//setLogoInfoHandle(logoEnv);
	//sleep(10);
	texthandle = getTextInfoHandle();
	readTextFromfile(ADDTEXT_FILE, texthandle);
	//	DEBUG(DL_DEBUG, "%d,%d,%d,%d,%d,%d,%s\n", DHCPVAL, texthandle->xpos, texthandle->ypos,
	//	      texthandle->enable, texthandle->showtime, texthandle->alpha, texthandle->msgtext);
	//	sleep(10);
#ifdef DSS_ENC_1100_1200
	ReadProtocolIni(PROTOCOL_NAME, &gProtocol);
#endif

	ReadRemoteCtrlIndex(REMOTE_NAME, &index);
	/*Read I frames Interval*/
	ReadIframeInterval(IFRAMES_NAME);
	/*green Save Module*/
	app_init_green_adjust_module();
#ifdef CL4000_DVI
	app_init_screen_adjust_module();
#endif
	gblSetRemoteIndex(index);
	ReadHVTable(&gHVTable, 0);
	ReadHVTable(&gHVTable, 1);
#ifdef CL4000_DVI_SDI
	ReadIPParamTable(IP_PARAM, &gSysParaT);
#endif

	if(DHCPVAL) {
		printf("i will set dhcp.\n");
#if 1
		system("kill -1 `cat /var/run/dhcpcd-eth0.pid`");
		system("/sbin/dhcpcd eth0");
		system("ifconfig eth0");
#endif
		gSysParaT.sysPara.dwNetMark = GetNetmask("eth0");
		gSysParaT.sysPara.dwAddr = GetIPaddr("eth0");
		get_gateway(gateway);
		gSysParaT.sysPara.dwGateWay = 	get_gateway(gateway);
		DEBUG(DL_DEBUG, "gateway =%s\n", gateway);
	} else {
		printf("i will set static ip.\n");
		SetEthConfigIP(gSysParaT.sysPara.dwAddr, gSysParaT.sysPara.dwNetMark);
		SetEthConfigGW(gSysParaT.sysPara.dwGateWay);
	}

	system("ifconfig");

	strcpy(gSysParaT.sysPara.strVer, box_version);
	initSetParam();
	DEBUG(DL_DEBUG, "logo=%d text=%d ,texthandle->enable=%d,texthandle->showtime=%d\n", outputhandle.logo_show, outputhandle.text_show, texthandle->enable, texthandle->showtime);
#ifdef DSS_ENC_1100_1200
	/*open lcd initial*/
	OpenLCDCom(); //matchbox ++
	gblLoadIDX(); //matchbox ++

	if(-2 == ReadDeviceType(DTYPECONFIG_NAME, 1)) {
		ReadDeviceType(DTYPECONFIG_NAME, 0);
	}

	GetDeviceType(devicebuf);
	DEBUG(DL_DEBUG, "DTYPECONFIG_NAME gDeviceType = %s\n", devicebuf);
#endif

	/*取消PIPE坏的信号*/
	Signal(SIGPIPE, SIG_IGN);
	/* Set the priority of this whole process to max (requires root) */
	setpriority(PRIO_PROCESS, 0, -20);
	/*初始化高码流视频编码库参数*/
	InitVideoEncParams(&gSysParaT.videoPara[PORT_ONE]);
	/*初始化低码流视频编码库参数*/
	InitLowRateParams(&gSysParaT.videoPara[PORT_TWO]);
	/*初始化音频编码库参数*/
	InitAudioEncParams(&gSysParaT.audioPara[PORT_ONE]);
	/* Initialize the mutex which protects the global data */
	pthread_mutex_init(&gbl.mutex, NULL);
	/* Initialize Codec Engine runtime */
	CERuntime_init();
	/* Initialize Davinci Multimedia Application Interface */
	Dmai_init();
	closeWatchDog();

	mid_timer_init();
		
	initWatchDog();
#ifdef CL4000_DVI_SDI

	if(gblGetRemoteIndex() < MAX_FAR_CTRL_NUM) {
		result = InitRemoteStruct(gblGetRemoteIndex());
	}

	gRemoteFD = CameraCtrlInit(PORT_COM2);

	if(gRemoteFD <= 0) {
		DEBUG(DL_ERROR, "Initial CameraCtrlInit() Error\n");
	}

#else
#ifndef ENABLE_DEUBG

	if(gblGetRemoteIndex() < MAX_FAR_CTRL_NUM) {
		result = InitRemoteStruct(gblGetRemoteIndex());
	}

	gRemoteFD = CameraCtrlInit(PORT_COM1);

	if(gRemoteFD <= 0) {
		DEBUG(DL_ERROR, "Initial CameraCtrlInit() Error\n");
	}

#endif
#endif
	CreateTCPTask(id_listen);
	/* Initialize the logs. Must be done after CERuntime_init() */
	/*  if(TraceUtil_start(engine->engineName) != TRACEUTIL_SUCCESS)
		{
		    ERR("Failed to TraceUtil_start\n");
			cleanup(EXIT_FAILURE);
		}	*/
	//initMask |= LOGSINITIALIZED;
	app_set_logoshow_flag(outputhandle.logo_show);
	app_set_textshow_flag(outputhandle.text_show)	;
	//setShowLogoTextFlag(outputhandle->logotext);
	addtextdisplay(texthandle);
	/* Determine the number of threads needing synchronization */
	numThreads = 1;
	/*视频线程个数*/
	numThreads += 7;
	/*音频线程个数*/
	numThreads += 1;

	/* Create the objects which synchronizes the thread init and cleanup */
	hRendezvousInit = Rendezvous_create(numThreads, &rzvAttrs);
	hRendezvousCleanup = Rendezvous_create(numThreads, &rzvAttrs);
	hRendezvousWriter = Rendezvous_create(3, &rzvAttrs);

	if(hRendezvousInit == NULL ||
	   hRendezvousCleanup == NULL ||
	   hRendezvousWriter == NULL) {
		ERR("Failed to create Rendezvous objects\n");
		cleanup(EXIT_FAILURE);
	}

	/* Initialize the thread attributes */
	if(pthread_attr_init(&attr)) {
		ERR("Failed to initialize thread attrs\n");
		cleanup(EXIT_FAILURE);
	}

	/* Force the thread to use custom scheduling attributes */
	if(pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)) {
		ERR("Failed to set schedule inheritance attribute\n");
		cleanup(EXIT_FAILURE);
	}

	/* Set the thread to be fifo real time scheduled */
	if(pthread_attr_setschedpolicy(&attr, SCHED_FIFO)) {
		ERR("Failed to set FIFO scheduling policy\n");
		cleanup(EXIT_FAILURE);
	}


	/* Create the capture fifos */
	captureEnv.to_video_c = Fifo_create(&fAttrs);
	captureEnv.from_video_c = Fifo_create(&fAttrs);
	captureEnv.to_resize_c = Fifo_create(&fAttrs);
	captureEnv.from_resize_c = Fifo_create(&fAttrs);

	if(captureEnv.to_video_c == NULL || captureEnv.from_video_c == NULL ||
	   captureEnv.to_resize_c == NULL || captureEnv.from_resize_c == NULL) {
		ERR("Failed to open display fifos\n");
		cleanup(EXIT_FAILURE);
	}

	LowRateResize.to_videoresize_c = Fifo_create(&fAttrs);
	LowRateResize.from_videoresize_c = Fifo_create(&fAttrs);

	if(LowRateResize.to_videoresize_c == NULL || LowRateResize.from_videoresize_c == NULL) {
		ERR("Failed to open Resize fifos\n");
		cleanup(EXIT_FAILURE);
	}

	/* Set the capture thread priority */
	schedParam.sched_priority = CAPTURE_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	/* Create the capture thread */
	captureEnv.hRendezvousInit    = hRendezvousInit;
	captureEnv.hRendezvousCleanup = hRendezvousCleanup;
	DEBUG(DL_DEBUG, "captureThrFxn thread!!!!\n");


	if(pthread_create(&captureThread, &attr, captureThrFxn, &captureEnv)) {
		ERR("Failed to create capture thread\n");
		cleanup(EXIT_FAILURE);
	}

	/* Create the writer fifos */
	writerEnv.to_video_c = Fifo_create(&fAttrs);
	writerEnv.from_video_c = Fifo_create(&fAttrs);
	writerLowRateEnv.to_writelow_c = Fifo_create(&fAttrs);
	writerLowRateEnv.from_writelow_c = Fifo_create(&fAttrs);

	if(writerEnv.to_video_c == NULL || writerEnv.from_video_c == NULL ||
	   writerLowRateEnv.to_writelow_c == NULL || writerLowRateEnv.from_writelow_c == NULL) {
		ERR("Failed to open display fifos\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= CAPTURETHREADCREATED ;
	/*detect thread*/
	detectEnv.hRendezvousInit	  = hRendezvousInit;
	detectEnv.hRendezvousCleanup  = hRendezvousCleanup;

	/* Set the video thread priority */
	schedParam.sched_priority = DETECT_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	if(pthread_create(&detectThread, &attr, detectThrFxn, &detectEnv)) {
		ERR("Failed to create detect thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= DETECTTHREADCREATED ;

	/* Set the video thread priority */
	schedParam.sched_priority = VIDEO_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	DEBUG(DL_DEBUG, "videoThrFxn thread!!!!\n");

	/* Create the video thread */
	videoEnv.hRendezvousInit    = hRendezvousInit;
	videoEnv.hRendezvousCleanup = hRendezvousCleanup;
	videoEnv.hRendezvousWriter  = hRendezvousWriter;
	videoEnv.to_capture    		= captureEnv.from_video_c;
	videoEnv.from_capture     	= captureEnv.to_video_c;
	videoEnv.to_writer     		= writerEnv.from_video_c;
	videoEnv.from_writer     	= writerEnv.to_video_c;
	videoEnv.videoEncoder       = engine->videoEncoders->codecName;
	videoEnv.engineName         = engine->engineName;


	if(pthread_create(&videoThread, &attr, videoThrFxn, &videoEnv)) {
		ERR("Failed to create video thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= VIDEOTHREADCREATED;

	/* Create the videoResize thread */
	videoLowRateEnv.hRendezvousInit    = hRendezvousInit;
	videoLowRateEnv.hRendezvousCleanup = hRendezvousCleanup;
	videoLowRateEnv.hRendezvousWriter  = hRendezvousWriter;
	videoLowRateEnv.to_resize		  = LowRateResize.from_videoresize_c;
	videoLowRateEnv.from_resize		  = LowRateResize.to_videoresize_c;
	videoLowRateEnv.from_writer    	  = writerLowRateEnv.to_writelow_c;
	videoLowRateEnv.to_writer          = writerLowRateEnv.from_writelow_c;
	videoLowRateEnv.videoEncoder       = engine->videoEncoders->codecName;
	videoLowRateEnv.engineName         = engine->engineName;
	DEBUG(DL_DEBUG, "videoLowRateThrFxn thread!!!!\n");

	if(pthread_create(&videoLowThread, &attr, videoLowRateThrFxn, &videoLowRateEnv)) {
		ERR("Failed to create video thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= VIDEOLOWRATETHREAD;

	/* Create the video thread */
	LowRateResize.hRendezvousInit    = hRendezvousInit;
	LowRateResize.hRendezvousCleanup = hRendezvousCleanup;
	LowRateResize.hRendezvousWriter  = hRendezvousWriter;
	LowRateResize.from_capture		 = captureEnv.to_resize_c;
	LowRateResize.to_capture		 = captureEnv.from_resize_c;
	LowRateResize.videoEncoder       = engine->videoEncoders->codecName;
	LowRateResize.engineName         = engine->engineName;
	/* Set the video thread priority */
	schedParam.sched_priority = VIDEO_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	DEBUG(DL_DEBUG, "ResizeLowThrFxn thread!!!!\n");

	if(pthread_create(&resizeLowThread, &attr, ResizeLowThrFxn, &LowRateResize)) {
		ERR("Failed to create video thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= RESIZELOWRATETHREAD;

	Rendezvous_meet(hRendezvousWriter);

	/* Set the writer thread priority */
	schedParam.sched_priority = WRITER_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	/* Create the writer thread */
	writerEnv.hRendezvousInit    = hRendezvousInit;
	writerEnv.hRendezvousCleanup = hRendezvousCleanup;
	writerEnv.outBufSize         = videoEnv.outBufSize;

	DEBUG(DL_DEBUG, "writerThrFxn thread!!!!\n");

	if(pthread_create(&writerThread, &attr, writerThrFxn, &writerEnv)) {
		ERR("Failed to create writer thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= WRITERTHREADCREATED;

	/* Create the writer thread */
	writerLowRateEnv.hRendezvousInit         = hRendezvousInit;
	writerLowRateEnv.hRendezvousCleanup      = hRendezvousCleanup;
	writerLowRateEnv.outBufSize              = videoLowRateEnv.outBufSize;

	DEBUG(DL_DEBUG, "writerLowThrFxn thread!!!!\n");

	if(pthread_create(&writerLowThread, &attr, writerLowThrFxn, &writerLowRateEnv)) {
		ERR("Failed to create writerResize thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= WRITELOWRATETHREAD;

	/* Set the thread priority */
	schedParam.sched_priority = AUDIO_THREAD_PRIORITY;

	if(pthread_attr_setschedparam(&attr, &schedParam)) {
		ERR("Failed to set scheduler parameters\n");
		cleanup(EXIT_FAILURE);
	}

	DEBUG(DL_DEBUG, "Audio thread Function!!!!\n");
	/* Create the audio thread */
	audioEnv.hRendezvousInit    = hRendezvousInit;
	audioEnv.hRendezvousCleanup = hRendezvousCleanup;
	audioEnv.engineName         = engine->engineName;
	audioEnv.audioEncoder       = engine->audioEncoders->codecName;

	if(pthread_create(&audioThread, &attr, audioThrFxn, &audioEnv)) {
		ERR("Failed to create speech thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= AUDIOTHREADCREATED;
#ifdef DSS_ENC_1100_1200

	if(pthread_create(&webListenThread, &attr, weblistenThrFxn, NULL)) {
		ERR("Failed to create web listen thread\n");
		cleanup(EXIT_FAILURE);
	}

	initMask |= WEBLISTENCREATED;
#endif
	/* Main thread becomes the control thread */
	ctrlEnv.hRendezvousInit    = hRendezvousInit;
	ctrlEnv.hRendezvousCleanup = hRendezvousCleanup;
	ctrlEnv.engineName         = engine->engineName;
	ret = ctrlThrFxn(&ctrlEnv);

	if(ret == THREAD_FAILURE) {
		status = EXIT_FAILURE;
	}

	DEBUG(DL_DEBUG, "Exit All Thread!!\n");
cleanup:

	/* Make sure the other threads aren't waiting for init to complete */
	if(hRendezvousWriter) {
		Rendezvous_force(hRendezvousWriter);
	}

	if(hRendezvousInit) {
		Rendezvous_force(hRendezvousInit);
	}

	DEBUG(DL_DEBUG, "EXIT Common Mutex!!!\n");
	DestorygblCommonMutex();
	DEBUG(DL_DEBUG, "EXIT pthread Mutex!!!\n");
	DestroyMutexPthread();

	if(initMask & AUDIOTHREADCREATED) {
		if(pthread_join(audioThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	DEBUG(DL_DEBUG, "EXIT audio pThread!!!\n");

	if(initMask & VIDEOTHREADCREATED) {
		if(pthread_join(videoThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	DEBUG(DL_DEBUG, "EXIT video pThread!!!\n");

	if(initMask & WRITERTHREADCREATED) {
		if(pthread_join(writerThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	DEBUG(DL_DEBUG, "EXIT write pThread!!!\n");

	if(initMask & CAPTURETHREADCREATED) {
		if(pthread_join(captureThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	DEBUG(DL_DEBUG, "EXIT capture pThread!!!\n");

	if(initMask & VIDEOLOWRATETHREAD) {
		if(pthread_join(videoLowThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	if(initMask & RESIZELOWRATETHREAD) {
		if(pthread_join(resizeLowThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	if(initMask & WRITELOWRATETHREAD) {
		if(pthread_join(writerLowThread, &ret) == 0) {
			if(ret == THREAD_FAILURE) {
				status = EXIT_FAILURE;
			}
		}
	}

	if(pthread_join(id_listen[PORT_ONE], &ret) == 0) {
		if(ret == THREAD_FAILURE) {
			status = EXIT_FAILURE;
		}
	}

	if(captureEnv.to_video_c) {
		Fifo_delete(captureEnv.to_video_c);
	}

	if(captureEnv.from_video_c) {
		Fifo_delete(captureEnv.from_video_c);
	}

	if(captureEnv.to_resize_c) {
		Fifo_delete(captureEnv.to_resize_c);
	}

	if(captureEnv.from_resize_c) {
		Fifo_delete(captureEnv.from_resize_c);
	}

	if(writerEnv.to_video_c) {
		Fifo_delete(writerEnv.to_video_c);
	}

	if(writerEnv.from_video_c) {
		Fifo_delete(writerEnv.from_video_c);
	}

	if(writerLowRateEnv.from_writelow_c) {
		Fifo_delete(writerLowRateEnv.from_video_c);
	}

	if(writerLowRateEnv.to_writelow_c) {
		Fifo_delete(writerLowRateEnv.to_writelow_c);
	}

	if(LowRateResize.to_videoresize_c) {
		Fifo_delete(LowRateResize.to_videoresize_c);
	}

	if(LowRateResize.from_videoresize_c) {
		Fifo_delete(LowRateResize.from_videoresize_c);
	}

	DEBUG(DL_DEBUG, "EXIT Rendezvous cleanup pThread!!!\n");

	if(hRendezvousCleanup) {
		Rendezvous_delete(hRendezvousCleanup);
	}

	DEBUG(DL_DEBUG, "EXIT Rendezvous init pThread!!!\n");

	if(hRendezvousInit) {
		Rendezvous_delete(hRendezvousInit);
	}

	DEBUG(DL_DEBUG, "EXIT Rendezvous cleanup pThread!!!\n");
	/*
	    if (initMask & LOGSINITIALIZED) {
	        TraceUtil_stop();
		}	*/
	DEBUG(DL_DEBUG, "EXIT TraceUtil_stop !!!\n");
	pthread_mutex_destroy(&gbl.mutex);
	DEBUG(DL_DEBUG, "process EXIT!!!\n");
	exit(1);
}
Пример #19
0
pid_t __vfork(jmp_buf env)
{
    struct Task *this = FindTask(NULL);
    struct vfork_data *udata = AllocMem(sizeof(struct vfork_data), MEMF_ANY | MEMF_CLEAR);
    if(udata == NULL)
    {
	errno = ENOMEM;
	longjmp(env, -1);	
    }
    D(bug("__vfork: allocated udata %p\n", udata));
    bcopy(env, &udata->vfork_jump, sizeof(jmp_buf));

    struct TagItem tags[] =
    {
	{ NP_Entry,         (IPTR) launcher  },
	{ NP_CloseInput,    (IPTR) FALSE     },
	{ NP_CloseOutput,   (IPTR) FALSE     },
	{ NP_CloseError,    (IPTR) FALSE     },
        { NP_Cli,           (IPTR) TRUE      },
        { NP_Name,          (IPTR) "vfork()" },
        { NP_UserData,      (IPTR) udata     },
        { NP_NotifyOnDeath, (IPTR) TRUE      },
        { TAG_DONE,         0                }
    };

    udata->parent = this;
    
    struct arosc_privdata *ppriv = __get_arosc_privdata();
    udata->ppriv = ppriv;
    
    /* Store parent's vfork_data to restore it later */
    udata->prev = __get_arosc_privdata()->acpd_vfork_data;
    D(bug("__vfork: Saved old parent's vfork_data: %p\n", udata->prev));
                                        
    D(bug("__vfork: backuping startup buffer\n"));
    /* Backup startup buffer */
    CopyMem(&__aros_startup_jmp_buf, &udata->startup_jmp_buf, sizeof(jmp_buf));

    D(bug("__vfork: Allocating parent signal\n"));
    /* Allocate signal for child->parent communication */
    udata->parent_signal = AllocSignal(-1);
    if(udata->parent_signal == -1)
    {
	/* Couldn't allocate the signal, return -1 */
	FreeMem(udata, sizeof(struct vfork_data));
	errno = ENOMEM;
	longjmp(udata->vfork_jump, -1);    
    }
    
    D(bug("__vfork: Creating child\n"));
    udata->child = (struct Task*) CreateNewProc(tags);

    if(udata->child == NULL)
    {
	/* Something went wrong, return -1 */
	FreeMem(udata, sizeof(struct vfork_data));
	errno = ENOMEM; /* Most likely */
	longjmp(env, -1);
    }
    D(bug("__vfork: Child created %p, waiting to finish setup\n", udata->child));
    udata->child_id = GetETaskID(udata->child);
    D(bug("__vfork: Got unique child id: %d\n", udata->child_id));

    /* Wait for child to finish setup */
    Wait(1 << udata->parent_signal);
    
    if(udata->child_errno)
    {
	/* An error occured during child setup */
	errno = udata->child_errno;
	longjmp(env, -1);
    }
    
    D(bug("__vfork: Setting jmp_buf at %p in %p\n", __aros_startup, &__aros_startup_jmp_buf));
    if(setjmp(__aros_startup_jmp_buf))
    {
	D(bug("__vfork: child exited\n or executed\n"));

	if(!GETUDATA->child_executed)
	{
	    D(bug("__vfork: not executed\n"));
	    ((struct aros_startup*) GetIntETask(GETUDATA->child)->iet_startup)->as_startup_error = __aros_startup_error;
	    D(bug("__vfork: Signaling child\n"));
	    Signal(GETUDATA->child, 1 << GETUDATA->child_signal);
	}

	D(bug("__vfork: Waiting for child to finish using udata\n"));
	/* Wait for child to finish using GETUDATA */
	Wait(1 << GETUDATA->parent_signal);

	D(bug("__vfork: fflushing\n"));
	fflush(NULL);

	D(bug("__vfork: restoring old fd_array\n"));
	/* Restore parent's old fd_array */
	((struct arosc_privdata *) GetIntETask(GETUDATA->parent)->iet_acpd)->acpd_fd_mempool = GETUDATA->parent_acpd_fd_mempool;
	((struct arosc_privdata *) GetIntETask(GETUDATA->parent)->iet_acpd)->acpd_numslots = GETUDATA->parent_acpd_numslots;
	((struct arosc_privdata *) GetIntETask(GETUDATA->parent)->iet_acpd)->acpd_fd_array =  GETUDATA->parent_acpd_fd_array;

	D(bug("__vfork: restoring startup buffer\n"));
	/* Restore parent startup buffer */
	CopyMem(&GETUDATA->startup_jmp_buf, &__aros_startup_jmp_buf, sizeof(jmp_buf));

	D(bug("__vfork: freeing parent signal\n"));
	FreeSignal(GETUDATA->parent_signal);

        errno = GETUDATA->child_errno;
        
	FreeAndJump(GETUDATA);
	assert(0); /* not reached */
        return (pid_t) 1;
    }

    /* Remember parent fd descriptor table */
    udata->parent_acpd_fd_mempool = ppriv->acpd_fd_mempool;
    udata->parent_acpd_numslots = ppriv->acpd_numslots;
    udata->parent_acpd_fd_array = ppriv->acpd_fd_array;
    
    /* Pretend to be running as the child created by vfork */
    ppriv->acpd_vfork_data = udata;
    ppriv->acpd_flags |= PRETEND_CHILD;
    ppriv->acpd_fd_mempool = udata->cpriv->acpd_fd_mempool;
    ppriv->acpd_numslots = udata->cpriv->acpd_numslots;
    ppriv->acpd_fd_array = udata->cpriv->acpd_fd_array;
    
    D(bug("__vfork: Jumping to jmp_buf %p\n", &udata->vfork_jump));
    D(bug("__vfork: ip: %p, stack: %p\n", udata->vfork_jump[0].retaddr, udata->vfork_jump[0].regs[_JMPLEN - 1]));
    vfork_longjmp(udata->vfork_jump, 0);
    assert(0); /* not reached */
    return (pid_t) 0;
}
Пример #20
0
        if(spl >= sizeof(addr_un.sun_path))
        {
            LogError(
                "get_random_prngd: "
                "Random pool path is too long\n");
            return -1;
        }
        af = addr_un.sun_family = AF_UNIX;
        strncpy(addr_un.sun_path, socket_path, sizeof(addr_un.sun_path));
        addr_len = offsetof(struct sockaddr_un, sun_path) + spl + 1;
        addr = (struct sockaddr *)&addr_un;
    }
    else
        return -1;

    old_sigpipe = Signal(SIGPIPE, SIG_IGN);

    errors = 0;
    rval = -1;
reopen:
    if((fd = socket(af, SOCK_STREAM, 0)) < 0)
    {
        LogError("Couldn't create socket: %m\n");
        goto done;
    }

    if(connect(fd, (struct sockaddr *)addr, addr_len))
    {
        if(af == AF_INET)
            LogError("Couldn't connect to PRNGD port %d: %m\n", tcp_port);
        else
Пример #21
0
/*
 * main - The shell's main routine 
 */
int main(int argc, char **argv) 
{
    char c;
    char cmdline[MAXLINE];
    int emit_prompt = 1; /* emit prompt (default) */

    /* Redirect stderr to stdout (so that driver will get all output
     * on the pipe connected to stdout) */
    dup2(1, 2);

    /* Parse the command line */
    while ((c = getopt(argc, argv, "hvp")) != EOF) {
        switch (c) {
        case 'h':             /* print help message */
            usage();
	    break;
        case 'v':             /* emit additional diagnostic info */
            verbose = 1;
	    break;
        case 'p':             /* don't print a prompt */
            emit_prompt = 0;  /* handy for automatic testing */
	    break;
	default:
            usage();
	}
    }

    /* Install the signal handlers */

    /* These are the ones you will need to implement */
    Signal(SIGINT,  sigint_handler);   /* ctrl-c */
    Signal(SIGTSTP, sigtstp_handler);  /* ctrl-z */
    Signal(SIGCHLD, sigchld_handler);  /* Terminated or stopped child */

    /* This one provides a clean way to kill the shell */
    Signal(SIGQUIT, sigquit_handler); 

    /* Initialize the job list */
    initjobs(jobs);

    /* Execute the shell's read/eval loop */
    while (1) {

	/* Read command line */
	if (emit_prompt) {
	    printf("%s", prompt);
	    fflush(stdout);
	}
	if ((fgets(cmdline, MAXLINE, stdin) == NULL) && ferror(stdin))
	    app_error("fgets error");
	if (feof(stdin)) { /* End of file (ctrl-d) */
	    fflush(stdout);
	    exit(0);
	}

	/* Evaluate the command line */
	eval(cmdline);
	fflush(stdout);
	fflush(stdout);
    } 

    exit(0); /* control never reaches here */
}
Пример #22
0
static void __startup_detach(void)
{
    struct CommandLineInterface *cli;
    struct Process              *newproc;
    BPTR                         mysegment = NULL;
    STRPTR                       detached_name;

    D(bug("Entering __startup_detach(\"%s\", %d, %x)\n", argstr, argsize, SysBase));

    cli = Cli();
    /* Without a CLI detaching makes no sense, just jump to
       the real program.  */
    if (!cli)
    {
        __startup_entries_next();
    }  
    else
    {
        mysegment = cli->cli_Module;
        cli->cli_Module = NULL;

        detached_name = __detached_name ? __detached_name : (STRPTR)FindTask(NULL)->tc_Node.ln_Name;
    
        {
            struct TagItem tags[] =
            {
                { NP_Seglist,   (IPTR)mysegment            },
                { NP_Entry,     (IPTR)&__detach_trampoline },
                { NP_Name,      (IPTR)detached_name        },
                { NP_Arguments, (IPTR)__argstr             },
                { NP_Cli,       TRUE                       },
                { TAG_DONE,     0                          }
            };

            __detacher_process = (struct Process *)FindTask(NULL);

            /* CreateNewProc() will take care of freeing the seglist */
            newproc = CreateNewProc(tags);
        }

        if (!newproc)
        {
            cli->cli_Module = mysegment;
            __detached_return_value = RETURN_ERROR;
        }
        else
            while (!__detacher_go_away) Wait(SIGF_SINGLE);

        if (__detached_return_value != RETURN_OK)
        {
            PutStr(FindTask(NULL)->tc_Node.ln_Name); PutStr(": Failed to detach.\n");
        }
    
        if (newproc)
        {
            Forbid();
            Signal(&newproc->pr_Task, SIGF_SINGLE);
        }

        __aros_startup.as_startup_error = __detached_return_value;
    }

    D(bug("Leaving __startup_detach\n"));
}
Пример #23
0
void meetPassportClerk(int* isPassCleared, int socialNumber) {
	int i, currentClerkIndex;

	/* will talk to clerk now */
	currentClerkIndex = -1;
	while (currentClerkIndex == -1) {
		for (i = 0; i < passportClerkAmount; i++){
			Acquire(passportLocks[i]);
			if (GetMonitor(passportClerkState[i]) == AVAILABLE){
				currentClerkIndex = i;
				SetMonitor(passportClerkState[i], BUSY);
				break;
			} else {
				Release(passportLocks[i]);
			}
		}
		if (currentClerkIndex == -1) {
			punish(10,100); /* wait a little bit, someone will be available soon */
		}
	}

  Write("Senator ", 8, ConsoleOutput);
  WriteInt(socialNumber);
  Write(" has gotten in regular line for PassportClerk ", sizeof(" has gotten in regular line for PassportClerk "), ConsoleOutput);
  WriteInt(currentClerkIndex);
  Write("\n", 1, ConsoleOutput);

	SetMonitor(passportClerkDB[currentClerkIndex], socialNumber);

  Write("Senator ", 8, ConsoleOutput);
	WriteInt(socialNumber);
	Write(" has given SSN ", sizeof(" has given SSN "), ConsoleOutput);
	WriteInt(socialNumber);
	Write(" to passportClerk ", sizeof(" to passportClerk "), ConsoleOutput);
	WriteInt(currentClerkIndex);
	Write("\n", 1, ConsoleOutput);

	Signal(passportCV[currentClerkIndex], passportLocks[currentClerkIndex]);
	Wait(passportCV[currentClerkIndex], passportLocks[currentClerkIndex]);

	/*awoken */

	if (passportClerkDBCleared[currentClerkIndex]){
		/* that means cashier is notified that the previous */
		/* requirements have been completed and is cleared to continue */
		/* for user to pay and get checked off */
		Release(passportLocks[currentClerkIndex]);
		*isPassCleared = TRUE;
	} else {
		/* customer should NOT be here, punish the user */
		
		Write("Senator ", 8, ConsoleOutput);
		WriteInt(socialNumber);
		Write(" has gone to passportClerk ", sizeof(" has gone to passportClerk "), ConsoleOutput);
		WriteInt(currentClerkIndex);
		Write(" too soon. They are going to the back of the line.", sizeof(" too soon. They are going to the back of the line."), ConsoleOutput);
		Write("\n", 1, ConsoleOutput);

		Release(passportLocks[currentClerkIndex]);
		punish(100, 1000);
	}
}
Пример #24
0
/*
 * Simple forking HTTP proxy. It is an HTTP/1.0 proxy with knowledge of
 * HTTP/1.1. (The things lacking for HTTP/1.1 are the chunked transfer encoding
 * and the expect mechanism.) The proxy supports the CONNECT, GET, HEAD, and
 * POST methods. It supports Basic and Digest authentication of clients (use the
 * --proxy-auth option).
 *
 * HTTP/1.1 is defined in RFC 2616. Many comments refer to that document.
 * http://tools.ietf.org/html/rfc2616
 *
 * HTTP authentication is discussed in RFC 2617.
 * http://tools.ietf.org/html/rfc2617
 *
 * The CONNECT method is documented in an Internet draft and is specified as the
 * way to proxy HTTPS in RFC 2817, section 5.
 * http://tools.ietf.org/html/draft-luotonen-web-proxy-tunneling-01
 * http://tools.ietf.org/html/rfc2817#section-5
 *
 * The CONNECT method is not limited to HTTP, but is potentially capable of
 * connecting to any TCP port on any host. The proxy connection is requested
 * with an HTTP request, but after that, the proxy does no interpretation of the
 * data passing through it. See section 6 of the above mentioned draft for the
 * security implications.
 */
int ncat_http_server(void)
{
    int c, i, j;
    int listen_socket[NUM_LISTEN_ADDRS];
    socklen_t sslen;
    union sockaddr_u conn;

#ifndef WIN32
    Signal(SIGCHLD, proxyreaper);
#endif

#if HAVE_HTTP_DIGEST
    http_digest_init_secret();
#endif

#ifdef HAVE_OPENSSL
    if (o.ssl)
        setup_ssl_listen();
#endif
    /* Clear the socket list */
    for (i = 0; i < NUM_LISTEN_ADDRS; i++)
        listen_socket[i] = -1;

    /* set for selecting listening sockets */
    fd_set listen_fds;
    fd_list_t listen_fdlist;
    FD_ZERO(&listen_fds);
    init_fdlist(&listen_fdlist, num_listenaddrs);

    /* Listen on each address, set up lists for select */
    for (i = 0; i < num_listenaddrs; i++) {
        listen_socket[i] = do_listen(SOCK_STREAM, IPPROTO_TCP, &listenaddrs[i]);

        /* make us not block on accepts in wierd cases. See ncat_listen.c:209 */
        unblock_socket(listen_socket[i]);

        /* setup select sets and max fd */
        FD_SET(listen_socket[i], &listen_fds);
        add_fd(&listen_fdlist, listen_socket[i]);

    }

    for (;;) {
        fd_set read_fds;

        sslen = sizeof(conn.storage);
        /*
         * We just select to get a list of sockets which we can talk to
         */
        if (o.debug > 1)
            logdebug("selecting, fdmax %d\n", listen_fdlist.fdmax);
        read_fds = listen_fds;
        int fds_ready = fselect(listen_fdlist.fdmax + 1, &read_fds, NULL, NULL, NULL);

        if (o.debug > 1)
            logdebug("select returned %d fds ready\n", fds_ready);

        for (i = 0; i <= listen_fdlist.fdmax && fds_ready > 0; i++) {
            /* Loop through descriptors until there is something ready */
            if (!FD_ISSET(i, &read_fds))
                continue;

            /* Check each listening socket */
            for (j = 0; j < num_listenaddrs; j++) {
                if (i == listen_socket[j]) {
                    fds_ready--;
                    c = accept(i, &conn.sockaddr, &sslen);

                    if (c == -1) {
                        if (errno == EINTR)
                            continue;
                        die("accept");
                    }

                    if (!allow_access(&conn)) {
                        Close(c);
                        continue;
                    }
                    if (o.debug > 1)
                        logdebug("forking handler for %d\n", i);
                    fork_handler(i, c);
                }
            }
        }
    }
    return 0;
}
Пример #25
0
static void
Slave( struct ExecBase* SysBase )
{
  struct AHIAudioCtrlDrv* AudioCtrl;
  struct DriverBase*      AHIsubBase;
  struct AROSBase*        AROSBase;
  BOOL                    running;
  ULONG                   signals;

  int bytes_in_buffer  = 0;
  int offset_in_buffer = 0;

  AudioCtrl  = (struct AHIAudioCtrlDrv*) FindTask( NULL )->tc_UserData;
  AHIsubBase = (struct DriverBase*) dd->ahisubbase;
  AROSBase   = (struct AROSBase*) AHIsubBase;

  dd->slavesignal = AllocSignal( -1 );

  if( dd->slavesignal != -1 )
  {
    // Everything set up. Tell Master we're alive and healthy.

    Signal( (struct Task*) dd->mastertask,
            1L << dd->mastersignal );

    running = TRUE;

    // The main playback loop follow

    while( running )
    {      
      signals = SetSignal(0L,0L);

//    KPrintF("++++ arosdriver_after signal checking\n");
      if( signals & ( SIGBREAKF_CTRL_C | (1L << dd->slavesignal) ) )
      {
        running = FALSE;
      }
      else
      {
	int skip_mix;
	int bytes_avail;
	
	// First Delay() until there is at least one fragment free

	while( TRUE )
	{
	  int frag_avail, frag_alloc, frag_size;
	
	  OSS_GetOutputInfo( &frag_avail, &frag_alloc, &frag_size,
			     &bytes_avail );
	  
//	  KPrintF( "%ld fragments available, %ld alloced (%ld bytes each). %ld bytes total\n", frag_avail, frag_alloc, frag_size, bytes_avail );
	  
	  if( frag_avail == 0 )
	  {
	    // This is actually quite a bit too long delay :-( For
	    // comparison, the SB Live/Audigy driver uses 1/1000 s
	    // polling ...
//	    KPrintF("Delay\n");
    	  #if USE_TIMERTICK
	    SmallDelay(SysBase);
	  #else
	    Delay( 1 );
	  #endif
	  }
	  else
	  {
	    break;
	  }
	}

	skip_mix = 0;/*CallHookA( AudioCtrl->ahiac_PreTimerFunc,
		       (Object*) AudioCtrl, 0 );*/

	while( bytes_avail > 0 )
	{
//	  KPrintF( "%ld bytes in current buffer.\n", bytes_in_buffer );
	  
	  if( bytes_in_buffer == 0 )
	  {
	    int skip     = 0;
	    int offset   = 0;

	    int samples  = 0;
	    int bytes    = 0;
	  
	    int i;
	  
	    WORD* src;
	    WORD* dst;

	    CallHookPkt( AudioCtrl->ahiac_PlayerFunc, AudioCtrl, NULL );

	    samples = AudioCtrl->ahiac_BuffSamples;
	    bytes   = samples * 2; // one 16 bit sample is 2 bytes

	    switch( AudioCtrl->ahiac_BuffType )
	    {
	      case AHIST_M16S:
		skip = 1;
		offset = 0;
		break;
	    
	      case AHIST_M32S:
		skip = 2;
		offset = 1;
		break;

	      case AHIST_S16S:
		skip = 1;
		offset = 0;
		samples *= 2;
		bytes *= 2;
		break;

	      case AHIST_S32S:
		skip = 2;
		offset = 1;
		samples *= 2;
		bytes *= 2;
		break;
	    }

	    bytes_in_buffer  = bytes;
	    offset_in_buffer = 0;

	    if( ! skip_mix )
	    {
	      CallHookPkt( AudioCtrl->ahiac_MixerFunc, AudioCtrl,
			   dd->mixbuffer );
	    }

	    src = ((WORD*) dd->mixbuffer) + offset;
	    dst = dd->mixbuffer;

	    for( i = 0; i < samples; ++i )
	    {
	      *dst++ = *src;
	      src += skip;
	    }

//	    KPrintF( "Mixed %ld/%ld new bytes/samples\n", bytes, samples );
	  }

	  while( bytes_in_buffer > 0 &&
		 bytes_avail > 0 )
	  {
	    int written;
    	    int counter = 0;
    	    do
	    {
	    	written = OSS_Write( dd->mixbuffer + offset_in_buffer,
				    min( bytes_in_buffer, bytes_avail ) );
	    	if (counter > 10)
		{
		    if (written < 0) written = 0;
		    break;
		}
		
		if (written < 0) KPrintF("OSS_Write returned %ld. counter %ld  bytes_in_buffer %ld  bytes_avail %ld\n",
		    	    	written, counter, bytes_in_buffer, bytes_avail);
		
		counter++;
		
    	    } while (written < 0);
	    
	    bytes_in_buffer  -= written;
	    offset_in_buffer += written;
	    bytes_avail      -= written;
	    
//	    KPrintF( "Wrote %ld bytes (%ld bytes in buffer, offset=%ld, %ld bytes available in OSS buffers\n",
//		     written, bytes_in_buffer, offset_in_buffer, bytes_avail );
	  }
	}

	CallHookA( AudioCtrl->ahiac_PostTimerFunc, (Object*) AudioCtrl, 0 );
      }
    }
  }

  FreeSignal( dd->slavesignal );
  dd->slavesignal = -1;

  Forbid();

  // Tell the Master we're dying

  Signal( (struct Task*) dd->mastertask,
          1L << dd->mastersignal );

  dd->slavetask = NULL;

  // Multitaking will resume when we are dead.
}
Пример #26
0
Signal SignalSpace::get_signal_at_coordinate(double x, double y)
{
    return Signal(sqrt(x * x + y * y), freq, -atan(y / x));
}
Пример #27
0
void main()
{




    int i;
    int x;		/*for loop index*/
    int seed;	/*for generating random amount of wait time*/
    int bagTokenNo;
    int noCustomersServed=0;


    M.mCash=InitialManagerCash;
    M.mID=noOrderTakers ;

    /*Manager as an OrderTaker Initialization*/

    /*OrderTaker OT[i] becomes active only when manager works as an ordertaker*/


    /*MANAGER ENTERS SYSTEM*/

    while (1)
    {
        Acquire(customerCounterLock);

        if (customerCounter == noCustomers)
        {
            for (x=0; x<1000; x++)
                Yield();

            Halt();
        }
        Release(customerCounterLock);

        /* ************MANAGER AS AN ORDERTAKER STARTS HERE*************** */


        if (custLineLengthMV > 3)		/*More than 3 customers waiting*/
        {

            noOrderTakers++;

            orderTakerLock[M.mID]=CreateLock("OrderTaker_Lock",15);		/*orderTakerLock Created*/
            orderTakerCV[M.mID]=CreateCondition("Order_Taker_CV",14);	/*orderTakerCV Created*/


            OT[M.mID].otStatusMV=OTBusy;
            OT[M.mID].otID=M.mID;                			/*OrderTaker's ID - otID goes like 1, 2, 3, ....*/
            OT[M.mID].otTokenNo=-1;				/*Initialized to -1 as no Token No. given right now*/
            OT[M.mID].otCash=0;

            /* **************START OF ORDERTAKER CODE************* */



            while(noCustomersServed <= 2)
            {   /*OT works continuously, checking to see if he has*/  											/*served 2 customers*/
                Acquire(custLineLock); 			/*OT acquires custLineLock so that he can */
                /*later signal the waiting Customer*/


                if (custLineLengthMV > 0)        		/*i.e. someone's waiting in the line*/
                {
                    custLineLengthMV--; 			/*CustLineLength decremented as a */
                    /*customer has ended witing in line*/
                    OT[M.mID].otStatusMV=OTWaiting;		/*OT[i] is now in 'Waiting' state as it */
                    /*has already signaled */

                    Signal(custWaitingCV, custLineLock); 	/*OT Signals Customer*/


                }

                else if (ITEMSINQ > 0)
                {

                    noCustomersServed++;

                    Acquire(baggerQueueLock);
                    bagTokenNo=RemoveList(baggerQueue);
                    ITEMSINQ--;
                    Release(baggerQueueLock);


                    Release(custLineLock);        /*Food is now bagged so the custLineLock is released*/


                    baggingFn(M.mID, bagTokenNo);		/*The bagging function takes care of */


                    continue;                		/*OrderTaker will continously bag food if */
                    /*there are any food	*/
                    /*items that need to be bagged*/
                }



                Acquire(orderTakerLock[M.mID]);    		/*OrderTaker i should enter the Critical */
                /*Region of Customer-Order*/
                /*taker interaction before the Customer does*/
                /*	if (custLineLock -> isHeldByCurrentThread())*/
                Release(custLineLock);    			/*OrderTaker is now in the Customer-OrderTaker*/
                /* Critical Region	*/
                /*hence, the custLineLock is no longer required*/

                Wait(orderTakerCV[M.mID],orderTakerLock[M.mID]);	/*OrderTaker i is waiting for Customer's */

                noCustomersServed++;

                Release(orderTakerLock[M.mID]);    		/*OrderTaker i releases the OrderTakerLock*/

            }                  					/*while(true) loop ends here */


            noOrderTakers--;					/*OT[i] is inactive now*/
            OT[M.mID].otStatusMV=OTFree;

        }								/*if condition ends here*/


        /* *Manager as OrderTaker ends here....... */
        if(sixBurgerAvailable<=foodthreshold)
        {

            for(i=0; i<noCooks; i++)
            {
                if(Coo[i].Status==0)
                {
                    Coo[i].Status=1;
                    Print("\nManager informs Cook %d to cook 6-dollar burger\n", Coo[i].cookid,0,0);
                    Print("\nCook %d is going to cook 6-dollar burger\n", Coo[i].cookid,0,0);
                    Acquire(cookManagerLock);
                    Signal(cookMCV,cookManagerLock);
                    Release(cookManagerLock);

                    break;
                }
                else if(Coo[i].Status==2)
                {
                    Coo[i].Status=1;
                    Print("Cook %d returned from break", Coo[i].cookid,0,0);
                    Print("\nManager informs Cook %d to cook 6-dollar burger\n", Coo[i].cookid,0,0);
                    Print("\nCook %d is going to cook 6-dollar burger\n", Coo[i].cookid,0,0);
                    Acquire(cookManagerLock);
                    Signal(cookMCV,cookManagerLock);
                    Release(cookManagerLock);
                    break;

                }
                else
                {
                    Yield();
                    break;
                }
            }
        }
        else
            /* compare the value with the specific amount in the inventory. make cook Sleep*/
        {
            for(i=0; i<noCooks; i++)
            {
                if(Coo[i].Status==0)
                {
                    Coo[i].Status==2;
                    Print("Cook %d is going on break", Coo[i].cookid,0,0);

                    break;
                }
            }
        }


        if(threeBurgerAvailable<=foodthreshold)
        {
            for(i=0; i<noCooks; i++)
            {
                if(Coo[i].Status==0)
                {
                    Coo[i].Status=1;
                    Print("\nManager informs Cook %d to cook 3-dollar burger\n", Coo[i].cookid,0,0);
                    Print("\nCook %d is going to cook 3-dollar burger\n", Coo[i].cookid,0,0);
                    Acquire(cookManagerLock);
                    Signal(cookMCV,cookManagerLock);
                    Release(cookManagerLock);

                    break;
                }
                else if(Coo[i].Status==2)
                {
                    Coo[i].Status=1;
                    Print("Cook %d returned from break", Coo[i].cookid,0,0);
                    Print("\nManager informs Cook %d to cook 3-dollar burger\n", Coo[i].cookid,0,0);
                    Print("\nCook %d is going to cook 3-dollar burger\n", Coo[i].cookid,0,0);
                    Acquire(cookManagerLock);
                    Signal(cookMCV,cookManagerLock);
                    Release(cookManagerLock);

                    break;
                }
                else
                {
                    Yield();
                    break;
                }
            }
        }

        else
        {
            for(i=0; i<noCooks; i++)
            {
                if(Coo[i].Status==0)
                {
                    Coo[i].Status==2;
                    Print("Cook %d is going on break", Coo[i].cookid,0,0);

                    break;
                }
            }
        }



        if(veggieBurgerAvailable<=foodthreshold)
        {
            for(i=0; i<noCooks; i++)
            {
                if(Coo[i].Status==0)
                {
                    Coo[i].Status=1;
                    Print("\nManager informs Cook %d to cook veggie burger\n", Coo[i].cookid,0,0);
                    Print("\nCook %d is going to cook veggie burger\n", Coo[i].cookid,0,0);
                    Acquire(cookManagerLock);
                    Signal(cookMCV,cookManagerLock);
                    Release(cookManagerLock);

                    break;
                }
                else if(Coo[i].Status==2)
                {
                    Coo[i].Status=1;
                    Print("Cook %d returned from break", Coo[i].cookid,0,0);
                    Print("\nManager informs Cook %d to cook veggie burger\n", Coo[i].cookid,0,0);
                    Print("\nCook %d is going to cook veggie burger\n", Coo[i].cookid,0,0);
                    Acquire(cookManagerLock);
                    Signal(cookMCV,cookManagerLock);
                    Release(cookManagerLock);

                    break;
                }
                else
                {
                    Yield();
                    break;
                }
            }
        }

        else
        {
            for(i=0; i<noCooks; i++)
            {
                if(Coo[i].Status==0)
                {
                    Coo[i].Status==2;
                    Print("Cook %d is going on break", Coo[i].cookid,0,0);

                    break;
                }
            }
        }

        if(frenchFriesAvailable<=foodthreshold)
        {
            for(i=0; i<noCooks; i++)
            {
                if(Coo[i].Status==0)
                {
                    Coo[i].Status=1;
                    Print("\nManager informs Cook %d to cook french fries\n", Coo[i].cookid,0,0);
                    Print("\nCook %d is going to cook french fries\n", Coo[i].cookid,0,0);
                    Acquire(cookManagerLock);
                    Signal(cookMCV,cookManagerLock);
                    Release(cookManagerLock);

                    break;
                }
                else if(Coo[i].Status==2)
                {
                    Coo[i].Status=1;
                    Print("Cook %d returned from break", Coo[i].cookid,0,0);
                    Print("\nManager informs Cook %d to cook french fries\n", Coo[i].cookid,0,0);
                    Print("\nCook %d is going to cook french fries\n", Coo[i].cookid,0,0);
                    Acquire(cookManagerLock);
                    Signal(cookMCV,cookManagerLock);
                    Release(cookManagerLock);

                    break;
                }
                else
                {
                    Yield();
                    break;
                }
            }
        }
        else
            /* compare the value with the specific amount in the inventory. make cook Sleep*/
        {
            for(i=0; i<noCooks; i++)
            {
                if(Coo[i].Status==0)
                {
                    Coo[i].Status==2;
                    Print("Cook %d is going on break", Coo[i].cookid,0,0);

                    break;
                }
            }
        }




        /* ************MANAGER AS AN ORDERTAKER ENDS HERE***************  */




        /* ***************MAINTAINING UNCOOKED STARTS******************* */

        Acquire(uncookedLock);		/*accessing noUncooked variable */

        if (noUncooked < UncookedThreshold)	/*if current uncooked < threshold */
        {

            /*check if cash available after collecting each OT's cash, i.e. removes each of the OT's cash & */
            /*adds it to his own cash */

            Acquire(otCashLock);

            for (x=0; x < noOrderTakers; x++)
            {
                M.mCash+=OT[x].otCash;
                OT[x].otCash=0;
            }

            Release(otCashLock);

            /* by this time, mCash has total cash in the system */

            /*cash reqd for this order=AddedQuantity * UncookedPrice*/

            while (noUncooked < UncookedThreshold)
            {

                if (M.mCash >  AddedQuantity * UncookedPrice )
                {
                    Release(uncookedLock);
                    /*enough cash to place an order */

                    /*order placed now, so cash decremented */
                    M.mCash -=AddedQuantity * UncookedPrice;

                    Print("\nManager refills the inventory\n",0,0,0);

                    /*Order placed !!*/

                    /*Time waiting for order to come*/

                    /*	while (1)		*/		/*seed is 1 or 2*/
                    /*	if (!(seed=rand() % 2))	*/	/*CAN TAKE MACRO IF TIME LATER !!!!*/
                    /*			break;
                    */

                    for (x=1; x <= seed * 5 * 2 ; x++)
                        Yield();

                    /*Wait is now over!!*/

                    Acquire(uncookedLock);
                    noUncooked+=AddedQuantity;

                    Print("\nInventory is loaded in the restaurant\n",0,0,0);

                    /*	if (uncookedLock -> isHeldByCurrentThread())	*/	/*NOT REQD but for backup*/
                    Release(uncookedLock);
                }

                else
                {
                    /*	if (uncookedLock -> isHeldByCurrentThread())	*/	/*NOT REQD but for backup*/
                    Release(uncookedLock);
                    /*NO Cash*/
                    /*Needs to go to the ATM*/
                    goToBankFn();
                    Acquire(uncookedLock);
                    /*Manager is now richer by CashWithdrawn*/
                }
            }						/*while loop ends here*/
        }							/*uncooked items ordered*/

        /*	if (uncookedLock -> isHeldByCurrentThread())	*/	/*NOT REQD but for backup*/
        Release(uncookedLock);


        /* ***************MAINTAINING UNCOOKED ENDS******************* */



        /* ******************************Waiter Manager Interaction */


        if(itemsInWaiterQueue > WaitingOrderThreshold)
        {

            Acquire(waiterLock);		/*Manager Waiter interaction Lock */



            Print("\nManager calls back all Waiters from break\n",0,0,0);

            Signal(waiterCV,waiterLock);

            Release(waiterLock);
        }
        Yield();
    }







}
Пример #28
0
int main(int argc, char **argv) 
{
    int listenfd,connfd, port,clientlen;
    pid_t pid;
    struct sockaddr_in clientaddr;
    char isdaemon=0,*portp=NULL,*logp=NULL,tmpcwd[MAXLINE];

    #ifdef HTTPS 
    int sslport;
    char dossl=0,*sslportp=NULL;
    #endif

    openlog(argv[0],LOG_NDELAY|LOG_PID,LOG_DAEMON);	
    cwd=(char*)get_current_dir_name();	
    strcpy(tmpcwd,cwd);
    strcat(tmpcwd,"/");
    /* parse argv */

    #ifdef  HTTPS
    parse_option(argc,argv,&isdaemon,&portp,&logp,&sslportp,&dossl);
    sslportp==NULL ?(sslport=atoi(Getconfig("https"))) : (sslport=atoi(sslportp));

    if(dossl==1||strcmp(Getconfig("dossl"),"yes")==0)
    	dossl=1;
    #else
    parse_option(argc,argv,&isdaemon,&portp,&logp);
    #endif

    portp==NULL ?(port=atoi(Getconfig("http"))) : (port=atoi(portp));


    Signal(SIGCHLD,sigChldHandler);


    /* init log */
    if(logp==NULL) 
    	logp=Getconfig("log");
    initlog(strcat(tmpcwd,logp));

    /* whethe show dir */
    if(strcmp(Getconfig("dir"),"no")==0)
    	isShowdir=0;	
    	

    clientlen = sizeof(clientaddr);


    if(isdaemon==1||strcmp(Getconfig("daemon"),"yes")==0)
    	Daemon(1,1);

    writePid(1);

    /* $https start  */ 
    #ifdef HTTPS 
    if(dossl)
    {
    	if((pid=Fork())==0)
	{
		listenfd= Open_listenfd(sslport);
		ssl_init();

		while(1)
		{
			connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
			if(access_ornot(inet_ntoa(clientaddr.sin_addr))==0)
			{
				clienterror(connfd,"maybe this web server not open to you!" , "403", "Forbidden", "Tiny couldn't read the file");
				continue;
			}

			if((pid=Fork())>0)
			{
				Close(connfd);
				continue;
			}
			else if(pid==0)
			{
				ishttps=1;	
				doit(connfd);
				exit(1);
			}
		}
	}
    }
    #endif

    /* $end https */


    listenfd = Open_listenfd(port);
    while (1)
    {
	connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
	if(access_ornot(inet_ntoa(clientaddr.sin_addr))==0)
	{
	    clienterror(connfd,"maybe this web server not open to you!" , "403", "Forbidden", "Tiny couldn't read the file");
	    continue;
	}

	if((pid=Fork())>0)
	{
		Close(connfd);
		continue;
	}
	else if(pid==0)
	{
		doit(connfd);
		exit(1);
	}
    }
}
Пример #29
0
/** Wait for an event and process it. */
void WaitForEvent(XEvent *event) {

   struct timeval timeout;
   fd_set fds;
   int fd;
   int handled;

   fd = JXConnectionNumber(display);

   do {

      while(JXPending(display) == 0) {
         FD_ZERO(&fds);
         FD_SET(fd, &fds);
         timeout.tv_usec = 0;
         timeout.tv_sec = 1;
         if(select(fd + 1, &fds, NULL, NULL, &timeout) <= 0) {
            Signal();
         }
      }

      Signal();

      JXNextEvent(display, event);

      switch(event->type) {
      case ConfigureRequest:
         HandleConfigureRequest(&event->xconfigurerequest);
         handled = 1;
         break;
      case MapRequest:
         HandleMapRequest(&event->xmap);
         handled = 1;
         break;
      case PropertyNotify:
         handled = HandlePropertyNotify(&event->xproperty);
         break;
      case ClientMessage:
         HandleClientMessage(&event->xclient);
         handled = 1;
         break;
      case UnmapNotify:
         HandleUnmapNotify(&event->xunmap);
         handled = 1;
         break;
      case Expose:
         handled = HandleExpose(&event->xexpose);
         break;
      case ColormapNotify:
         HandleColormapChange(&event->xcolormap);
         handled = 1;
         break;
      case DestroyNotify:
         handled = HandleDestroyNotify(&event->xdestroywindow);
         break;
      case SelectionClear:
         handled = HandleSelectionClear(&event->xselectionclear);
         break;
      case ResizeRequest:
         handled = HandleDockResizeRequest(&event->xresizerequest);
         break;
      case MotionNotify:
         SetMousePosition(event->xmotion.x_root, event->xmotion.y_root);
         handled = 0;
         break;
      case ReparentNotify:
         HandleDockReparentNotify(&event->xreparent);
         handled = 1;
         break;
      case ConfigureNotify:
         handled = 0;
         break;
      case CreateNotify:
      case MapNotify:
      case GraphicsExpose:
      case NoExpose:
         handled = 1;
         break;
      default:
#ifdef USE_SHAPE
         if(haveShape && event->type == shapeEvent) {
            HandleShapeEvent((XShapeEvent*)event);
            handled = 1;
         } else {
            handled = 0;
         }
#else
         handled = 0;
#endif
         break;
      }

      if(!handled) {
         handled = ProcessTrayEvent(event);
      }
      if(!handled) {
         handled = ProcessDialogEvent(event);
      }
      if(!handled) {
         handled = ProcessSwallowEvent(event);
      }
      if(!handled) {
         handled = ProcessPopupEvent(event);
      }

   } while(handled && !shouldExit);

}
Пример #30
0
int
main(int argc, char **argv)
{
        Signal( SIGINT, sigInt);
	int			i, maxi, maxfd, listenfd, connfd, sockfd;
	int			nready, client[FD_SETSIZE];
	ssize_t			n;
	fd_set			rset, allset;
	char			buf[MAXLINE];
	socklen_t		clilen;
	struct sockaddr_in	cliaddr, servaddr;

	listenfd = Socket(AF_INET, SOCK_STREAM, 0);

	bzero(&servaddr, sizeof(servaddr));
	servaddr.sin_family      = AF_INET;
	servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
	servaddr.sin_port        = htons(SERV_PORT);

        /* SO_REUSEADDR allows a new server to be started
         * on the same port as an existing server that is
         * bound to the wildcard address, as long as each
         * instance binds a different local IP address.
         * This is common for a site hosting multiple HTTP
         * servers using the IP alias technique */
        int reuseaddr_on = 1;
        if( setsockopt( listenfd, SOL_SOCKET, SO_REUSEADDR,
                &reuseaddr_on, sizeof( reuseaddr_on)) < 0)
        {
            // log
        }

	Bind( listenfd, (SA *) &servaddr, sizeof(servaddr));

	Listen( listenfd, LISTENQ);

	maxfd = listenfd;			/* initialize */
	maxi = -1;				/* index into client[] array */
	for ( i = 0; i < FD_SETSIZE; ++i)
		client[i] = -1;			/* -1 indicates available entry */
	FD_ZERO( &allset);
	FD_SET( listenfd, &allset);

	for ( ; ; ) {
		rset = allset;                  /* structure assignment */
                
                /* select waits for something to happen: either the establishment
                 * of a new client connection or the arrival of data, a FIN,
                 * or an RST on an existing connection */
		nready = Select( maxfd + 1, &rset, NULL, NULL, NULL);

		if ( FD_ISSET( listenfd, &rset)) {	/* new client connection */
                    
                    /* simulate busy server */
                    printf( "listening socket readable -> sleep(5)\n");
                    sleep(5);

                    /* If the listening socket is readable, a new connection has been 
                     * established. We call accept and update our data structures
                     * accordingly. We use the first unused entry in the client array
                     * to record the connected socket. The number of ready descriptors
                     * is decremented, and if it is 0, we can avoid the next for loop.
                     * This lets us use the return value from select to avoid checking
                     * descriptors that are not ready.*/
			clilen = sizeof( cliaddr);
                        printf( "accept called\n"); fflush( stdout);
			connfd = accept( listenfd, ( SA *) &cliaddr, &clilen);
                        printf( "accept returned, connfd=%d\n", connfd); fflush( stdout);

			for ( i = 0; i < FD_SETSIZE; ++i)
				if (client[i] < 0) {
					client[i] = connfd;	/* save descriptor */
					break;
				}
			if ( i == FD_SETSIZE)
				err_quit( "too many clients");

			FD_SET( connfd, &allset);	/* add new descriptor to set */
			if ( connfd > maxfd)
				maxfd = connfd;		/* for select */
			if ( i > maxi)
				maxi = i;		/* max index in client[] array */

			if ( --nready <= 0)
				continue;		/* no more readable descriptors */
		}

		for ( i = 0; i <= maxi; ++i) {	/* check all clients for data */
                    
                    /* A test is made for each existing client connection as to whether
                     * or not its descriptor is in the descriptor set returned by select.
                     * If so, a line is read from the client and echoed back to the client.
                     * If the client closes the connection, read returns 0 and we update
                     * our data structures accordingly. We never decrement the value
                     * of maxi, but we could check for this possibility each time a client
                     * closes its connection.*/
			if ( ( sockfd = client[i]) < 0)
				continue;
			if ( FD_ISSET( sockfd, &rset)) {
				if ( ( n = Read( sockfd, buf, MAXLINE)) == 0) {
					/* connection closed by client */
					Close( sockfd);
					FD_CLR( sockfd, &allset);
					client[i] = -1;
				} else
					Writen( sockfd, buf, n); /* echo */

				if ( --nready <= 0)
					break;		/* no more readable descriptors */
			}
		}
	}

    return 0;
}