コード例 #1
0
ファイル: os.c プロジェクト: saquib-khan/PostOffice
/****************************** MAIN THREAD'S CODE *********************************/
int main(int argc,char *argv[])
{
    int worker;
    pthread_t customerThreads[totalcustomers], postalWorkerThreads[totalPostalWorkers];
    int customerNo, postalWorkerNo;
	int custids[totalcustomers];
	int pwids[totalPostalWorkers];
    int errcode;
    int *status;

	//Initialise the semaphores
	initSemaphores();
	createQueues();


    // create the Customer threads
	for (customerNo=0; customerNo<totalcustomers; customerNo++) 
    {
		custids[customerNo]=customerNo;
        // create thread
        if (errcode = pthread_create(&customerThreads[customerNo],NULL,customer,&custids[customerNo]))
        {
            printf("Thread could not be created");
        }
	}
	
	// create the Postal Worker threads
    for (postalWorkerNo=0; postalWorkerNo<totalPostalWorkers; postalWorkerNo++) 
    {
		pwids[postalWorkerNo]=postalWorkerNo;
        // create thread
        if (errcode = pthread_create(&postalWorkerThreads[postalWorkerNo],NULL,postalWorker,&pwids[postalWorkerNo]))
        {
            printf("Thread could not be created");
        }
    }

	//join the customer threads as they exit
    for (customerNo=0; customerNo<totalcustomers; customerNo++)
    {
        if(errcode=pthread_join(customerThreads[customerNo],(void*)&status))
        {
           printf("Thread could not be joined");
        }
        
      //check thread's exit status, should be the same as the thread number for this example
        if (*status != customerNo) 
        {
			printf("Customer thread %d terminated abnormally\n\n",customerNo);
			exit(1);
        }
		else
		{
			printf("Customer %d joined\n",*status);
		}

    }
	
    return(0);
}
コード例 #2
0
ファイル: barbers.c プロジェクト: martinqo99/school
/**
 * Funkcia syncProcess vytvara procesy a synchronizuje ich.
 * @param param Struktura s vlastnostami pre procesy.
 * @return Chybovy navrat funkcie.
 */
int syncProcess(TParams *param)
{
  int error = EOK;           // Premmena pre chybu pri zdielanej pamati.
  param->mainpid = getpid(); // Proces id hlavneho programu.
  setSignals(getpid());      // Zachytenie signalov.
  signal(SIGCHLD, SIG_IGN);  // Ignorovanie sigchld a uvolnovanie procesov.

  // Inicializacia semaforov
  TMutx semaphores = {.mut0 = NULL, .mut1 = NULL, .mut2 = NULL ,.mut3 = NULL,
  .mut4 = NULL, .mut5 = NULL, .mut6 = NULL, .mut7 = NULL,};
  if(initSemaphores(&semaphores) != EOK)
  {
   destroySemaphores(&semaphores);
   return ESEMAP;
  }
  g_mutxs = &semaphores;

  // Vytvorenie zdielanej pamate.
  TSmem *memory = createSharedMem(&error,param,"/tmp");
  if(error) return ESHARED;
  g_mems = memory;
  g_shmid = param->sharedid;

  // Vytvorenie procesa holica.
  if((param->barberid = fork()) == -1)
  {
    destroySemaphores(&semaphores);
    unlinkSharedMem(memory,param->sharedid);
    return EFORK;
  }
  // Volanie holica.
  else if(param->barberid == 0)
  {
    syncBarber(memory, &semaphores, param);
    destroySemaphores(&semaphores);
    unlinkSharedMem(memory,param->sharedid);
    fclose(param->fw);
    exit(EXIT_SUCCESS);
  }
  // Vytvorenie procesov zakaznikov.
  else if(param->barberid > 0)
  {
    if(createCustomers(memory,param,&semaphores) == EFORK)
    {
      printECode(EFORK);
      kill(param->barberid, SIGUSR1);
      for(int i = 0; i < memory->created; i++)
        kill(memory->pids[0],SIGTERM);
      errorCleanAll(&semaphores,memory,param);
    }

    // Pockanie na proces barbra a uvolnenie zdielanej pamati.
    waitpid(param->barberid, NULL, 0);
    unlinkSharedMem(memory,param->sharedid);
    destroySemaphores(&semaphores);
  }
  return EOK;
}
コード例 #3
0
ファイル: api.c プロジェクト: VincentSmit/rts1
//Initialize the fifo adminstration.
void initFifoInfo(void* shmaddr)
{
	int i = 0;
	// Sets the base address for the administration of all the fifos
	info = (struct InfoFifo *) shmaddr;
	for(i = 0; i<NUM_FIFOS; i++)
	{
		// All Fifos have the same memory address for the administration.
		info[i].fifoAdminAddress = shmaddr;
	}

	initSemaphores(NUMBER_OF_LOCKS);
}
コード例 #4
0
ファイル: Scheduler.cpp プロジェクト: DayStarEngineering/CDH
int sched::configure()
{
	multimap<string,string>::iterator p,p2;
		
	// How many events are there:
	p = myConfig.find("event");
	p2 = myConfig.find("event");
	int ind = 0;
	if (p != myConfig.end())
	{
		do
		{
			++ind;
			++p;
		}
		while (p != myConfig.upper_bound("event"));
	}
	
	numEvents  = ind;
	if(numEvents <= 0)
	{
		myLogger.lw(ERROR,"CONFIG: Invalid number of events: %d, exiting...", numEvents);
		return -1;
	}
	else
	{
		myLogger.lw(INFO,"CONFIG: Creating space for %d events.", numEvents);
	}
	event = new schedEvent[numEvents];
	
	// Load all events:
	ind = 0;
	message tmpmsg;
	tmpmsg.rsp.length = 0;
	if (p2 != myConfig.end())
	{
		do
		{
			sscanf((*p2).second.c_str(),"%hhu %hhu %hhu  %hu %d %d",
			  &event[ind].cmd.proc,
			  &event[ind].cmd.type,
			  &event[ind].cmd.arg1,
			  &event[ind].cmd.arg2,
			  &event[ind].count,
			  &event[ind].sleep);

			// Error check:
			//if (event[ind].num != ind){ myLogger.lw(ERROR,"CONFIG: Improperly numbered task."); exit(-1); }

			// Print config:
			event[ind].num = ind;
			tmpmsg.cmd = event[ind].cmd;
			myLogger.lw(DEBUG,"CONFIG: Task %d, run %d time(s), sleep %d seconds, message: %s",
			  event[ind].num,
			  event[ind].count,
			  event[ind].sleep,
			  tmpmsg.toString());
			
			++p2;
			++ind;
		}
		while (p2 != myConfig.upper_bound("event"));
	}
	
	// Get location of globale variable files:
	playFname = myConfig["play_fname"].c_str();
	eventCounterFname = myConfig["event_counter_fname"].c_str();
	currEventFname = myConfig["curr_event_fname"].c_str();
	timeSleptFname = myConfig["time_slept_fname"].c_str();
	
	// Get semid:
	if( (sched_semid = initSemaphores(SCHED_PATH,NUM_SCHED)) == -1 )
	{
		myLogger.lw(WARNING,"CONFIG: Unable to grab semaphores (%s)", SCHED_PATH);
	}

	if( (semid = getSemaphoreID(KICK_PATH,NUM_KICK)) == -1)
    {
        myLogger.lw(WARNING,"CONFIG: Unable to grab semaphores (%s)", KICK_PATH);
    }
    else
    {
    	myLogger.lw(SPAM,"CONFIG: Got semid: %d",semid);
    }
    
	return 0;
}
コード例 #5
0
ファイル: Command.cpp プロジェクト: DayStarEngineering/CDH
void CommandWrapper::execute(message* msg)
{	
	// Lets prevent seggies...
	msg->rsp.length = 0;
				
	// Subsystem or Process??
	if(msg->cmd.proc >= TOT_PROC) // Subsystem Block
	{
		msg->err = 0;
		msg->qid = myqid;   // make sure the message come back to by queue
		msg->mtype = mytid; // unique message type for each process / thread
		
		if(msg->cmd.type == STATUS || msg->cmd.type == GET || msg->cmd.type == SET || msg->cmd.type == DATA)
		{
			// cout << msg->toString() << endl;
			if( msgQueueWrapper.msgQueueSend(ssmqid, msg) == -1 )
			{
				msg->rsp.ret = ERR_MSGQ_SEND;
				return;
			}
			
			if( msgQueueWrapper.msgQueueReceive(myqid, msg->mtype, msg) == -1 )
			{
				msg->rsp.ret = ERR_MSGQ_RECV;
				return;
			}
			// cout << msg->toString() << endl;
		}
		else if(msg->cmd.type == STOP || msg->cmd.type == START) // Run start/stop script
		{
			char action[1024];

			// Read in config file:
			configmap myConfig;
			myConfig.readfile("/home/conf/commandlist.xml");
		
			// Form action string:
			sprintf(action,"cmd_%d_%d",(unsigned int)msg->cmd.proc,(unsigned int)msg->cmd.type);

			// Execute action string in config file:
			msg->rsp.ret = system(myConfig[action].c_str())/256;
		
			// Is error?
			if(msg->rsp.ret >= 0xF0)
				msg->rsp.ret = msg->rsp.ret | 0xFFFFFF00;
		}
		else if(msg->cmd.type == SHUTDOWN)
		{
			 system("/home/scripts/rctest.sh; shutdown -P now"); // disable code from starting up again next boot.. and shutdown
		}
		else
		{
			msg->rsp.ret = ERR_INV_CMD_NAME;
		}
	}
	else                        // Process Block
	{
		// Cmd Line or Sem Execute??
		if(msg->cmd.type == STOP || msg->cmd.type == START || msg->cmd.type == STATUS)
		{
			char action[1024];
		
			// Read in config file:
			configmap myConfig;
			myConfig.readfile("/home/conf/commandlist.xml");

			// Check process number:
			if(msg->cmd.proc >= TOT_PROC)
			{
				msg->rsp.ret = ERR_INV_PROC_NAME;
				return;
			}
		
			// Form action string:
			sprintf(action,"cmd_%d_%d",(unsigned int)msg->cmd.proc,(unsigned int)msg->cmd.type);

			// Execute action string in config file:
			msg->rsp.ret = system(myConfig[action].c_str())/256;
		
			// Is error?
			if(msg->rsp.ret >= 0xF0)
				msg->rsp.ret = msg->rsp.ret | 0xFFFFFF00;
		}
		else if(msg->cmd.type == GET || msg->cmd.type == SET)
		{
			int semid;
			const char* path;
			int num_of_sem;
			int ret;
		
			// Get SEMID Vars:
			switch(msg->cmd.proc)
			{
				case ALL:
					msg->rsp.ret = ERR_CMD_DNE;
					return;
				
				case STPRO:
					num_of_sem  = NUM_STPRO;
					path = STPRO_PATH;
					break;
				
				case STCH:
					num_of_sem  = NUM_STCH;
					path = STCH_PATH;
					break;
				
				case HSKPR:
					num_of_sem  = NUM_HSKPR;
					path = HSKPR_PATH;
					break;
				
				case PDOG:
					num_of_sem  = NUM_PDOG;
					path = PDOG_PATH;
					break;
				
				case DCOL:
					num_of_sem  = NUM_DCOL;
					path = DCOL_PATH;
					break;
					
				case STIMG:
					num_of_sem  = NUM_STIMG;
					path = STIMG_PATH;
					break;
				
				case SCHED:
					num_of_sem  = NUM_SCHED;
					path = SCHED_PATH;
					break;
				
				default:
					msg->rsp.ret = ERR_INV_PROC_NAME;
					return;
			}
			
			// Get SEMID:
			if( (semid = initSemaphores(path,num_of_sem)) == -1 )
			{
				msg->rsp.ret = ERR_SEM_INIT;
				return;
			}
		
			// Check sem #:
			if( msg->cmd.arg1 >= num_of_sem )
			{
				msg->rsp.ret = ERR_SEM_DNE;
				return;
			}
			
			if( msg->cmd.type == GET )
			{
				if( (ret = getSemaphore(semid, msg->cmd.arg1)) <= -1 )
				{
					msg->rsp.ret = ERR_SEM_GET;
					return;
				}
				msg->rsp.ret = ret;
			}
			else
			{
				// Send command:
				if( setSemaphore(semid, msg->cmd.arg1, msg->cmd.arg2) <= -1 )
				{
					msg->rsp.ret = ERR_SEM_SET;
					return;
				}
				else
				{
					// Increment command count:
					int cmd_cnt;
					if( ( cmd_cnt = getSemaphore(semid, 0) ) <= -1 )
					{
						msg->rsp.ret = ERR_SEM_GET;
						return;
					}
					if( setSemaphore(semid, 0, cmd_cnt + 1) <= -1 )
					{
						msg->rsp.ret = ERR_SEM_SET;
						return;
					}
					msg->rsp.ret = 1;
				}
			}
		}
		else
		{
			msg->rsp.ret = ERR_INV_CMD_NAME;
			return;
		} 	
	}
}