示例#1
0
/* Allocate resources in request for process i, only if it 
   results in a safe state and return 1, else return 0 */
int resource_request(int i, int *request)
{
	printf("Process %d: ",i);
	printRequest(request);
	/*if (stateSafeCheck() == 0)
	{
		return 0;
	}*/
	int j;
	for (j = 0; j < col; j++) {
		// Step 1.
		if (request[j] > s->need[i][j]) {
			//ERROR
			printf("Request can't be granted, because the process has exceeded its maximum claim\n");
			return 0;
		}
	}
	
	for (j = 0; j < col; j++) {
		// Step 2.
		while (request[j] > s->available[j]) {
			//ERROR
			printf("No resources are available, therefore the process must wait!\n");
			sleep(100);
		}		
	}

	pthread_mutex_lock(&lock); // Lock the mutex.
	for (j = 0; j < col; j += 1)
	{
		// Step 3.
		s->available[j] -= request[j];
		s->allocation[i][j] += request[j];
		s->need[i][j] -= request[j];
	}
	
	if (stateSafeCheck() == 0)
	{
		for (j = 0; j < col; j += 1)
		{
			s->available[j] += request[j];
			s->allocation[i][j] -= request[j];
			s->need[i][j] += request[j];
		}
		pthread_mutex_unlock(&lock); // Unlock the mutex.
		return 0;
	}
	pthread_mutex_unlock(&lock); // Unlock the mutex.
	
	printAvailable();
	
	// Check if the resulting state is safe, return 1 if true, else 0.
	
  return 1;
}
示例#2
0
/* Release the resources in request for process i */
void resource_release(int i, int *request)
{
	printf("RELEASING RESOURCES!\n");
	printRequest(request);
	int j;
	pthread_mutex_lock(&lock); // Lock the mutex.
	for (j = 0; j < col; j++) {
		s->available[j] += request[j];
		s->allocation[i][j] -= request[j];
		s->need[i][j] += request[j];
	}
	pthread_mutex_unlock(&lock); // Unlock the mutex.
	
	printAvailable();
	
}
示例#3
0
int error_handler(mg_connection* conn, int status) {
    if (status == 304) {
        // 304 is a request for a value that has not changed since last sent to the client.
        // This is a normal condition for a correctly operating program.

        // debugPrintf("Connection 0x%x: HTTP error %d\n", (unsigned int)(uintptr_t)conn, status);

        const String& content = "Not modified";
        mg_printf(conn, 
                  "HTTP/1.1 304 NOT MODIFIED\r\n"
                  "Content-Type: text/html\r\n"
                  "Content-Length: %d\r\n"
                  "\r\n"
                  "%s", (int)content.size(), content.c_str());
    } else {
        debugPrintf("Connection 0x%x: HTTP error %d\n", (unsigned int)(uintptr_t)conn, status);
        const struct mg_request_info* ri = mg_get_request_info(conn);
        printRequest(ri);

        if (status == 500) {
            // The client already closed the connection
            return 0;
        }

        const String& content =
            format("<html><head><title>Illegal URL</title></head><body>Illegal URL (error %d)</body></html>\n", status);

        mg_printf(conn, 
                  "HTTP/1.1 200 OK\r\n"
                  "Content-Type: text/html\r\n"
                  "Content-Length: %d\r\n"
                  "\r\n"
                  "%s", (int)content.size(), content.c_str());

    }

    // Returning non-zero tells civetweb that our function has replied to
    // the client, and civetweb should not send client any more data.
    return 1;
}
OsagoMaster::OsagoMaster(QObject *parent) :
    QObject(parent)
{
    dialogs.push_back(new osagoCalcForm(&data));
    dialogs.push_back(new OsagoBlankDataForm(&data.insurancer,Driver::Insurancer, &data.insurancerIsOwner));
    dialogs.push_back(new OsagoBlankDataForm(&data.owner,Driver::Owner, &data.insurancerIsOwner));
    dialogs.push_back(new OsagoTsBlank(&data.transport, &data.insurancerIsOwner));
    dialogs.push_back(new OsagoUsingInfoForm(&data));
    connect(qobject_cast<osagoCalcForm*>(dialogs.at(0)), SIGNAL(next()), this, SLOT(next()));
    connect(qobject_cast<OsagoBlankDataForm*>(dialogs.at(1)), SIGNAL(prev()), this, SLOT(prev()));
    connect(qobject_cast<OsagoBlankDataForm*>(dialogs.at(1)), SIGNAL(next(int)), this, SLOT(next(int)));
    connect(qobject_cast<OsagoBlankDataForm*>(dialogs.at(2)), SIGNAL(prev()), this, SLOT(prev()));
    connect(qobject_cast<OsagoBlankDataForm*>(dialogs.at(2)), SIGNAL(next(int)), this, SLOT(next(int)));
    connect(qobject_cast<OsagoTsBlank*>(dialogs.at(3)), SIGNAL(prev(int)), this, SLOT(prev(int)));
    connect(qobject_cast<OsagoTsBlank*>(dialogs.at(3)), SIGNAL(next()), this, SLOT(next()));
    connect(qobject_cast<OsagoUsingInfoForm*>(dialogs.at(4)), SIGNAL(prev()), this, SLOT(prev()));
    connect(qobject_cast<OsagoUsingInfoForm*>(dialogs.at(4)), SIGNAL(printRequest()), this, SLOT(printRequest()));
    connect(qobject_cast<OsagoUsingInfoForm*>(dialogs.at(4)), SIGNAL(printBlank()), this, SLOT(printBlank()));
    dialogs.at(0)->show();
    foreach (QDialog* dial, dialogs) {
        dial->setModal(true);
    }
示例#5
0
GroupWidget::GroupWidget(Group* g, MainWindow* w):QWidget()
{
	group = g;
	mW = w;
	std::vector<int> ploplop;
	std::vector<int>* vect = g->getVect();
	kontacts = new std::vector<Kontact*>;
	Kontact* kon;
	int i;
	int n = vect->size();
	for(i=0; i<n; ++i)
	{
		kon = w->askKontact( (*vect)[i] );
		if(kon != 0)
			kontacts->push_back(kon);
		ploplop.push_back( (*vect)[i] );
	}
	//ici algo foireux
	std::vector<int>* ginc = g->getInclusion();
	i = 0;
	int k,j;
	Group* gBis;
	std::vector<int> protection;
	protection.push_back( g->getId() );
	while( i  < ginc->size() )
	{
		//On inclut les contact du groupe
		gBis = mW->getGroupById((*ginc)[i]);
		if( gBis!= 0 )
		{
			k = gBis->getVect()->size();
			protection.push_back( gBis->getId() );
			for(j=0; j<k; ++j)
			{
				if( !contains( ploplop, (*(gBis->getVect()))[j] ) )
				{
					kon = w->askKontact( (*(gBis->getVect()))[j] );
					if(kon != 0)
					kontacts->push_back(kon);
					ploplop.push_back( (*(gBis->getVect()))[j] );
				}
			}
			k= gBis->getInclusion()->size();;
			for(j=0; j<k; ++j)
			{
				if( !contains(protection, (*(gBis->getInclusion()))[j]) )
					ginc->push_back( (*(gBis->getInclusion()))[j] );
			}
		}
		++i;
	}
	//retour à la normale
	sort( kontacts->begin(), kontacts->end(), rel);
	titre = new QLabel;
	titre->setText(tr("<h1>Groupe ")+ g->getName() +"</h1>");
	titre->setTextInteractionFlags( Qt::TextSelectableByMouse );
	titleLayout = new QHBoxLayout;
	imageButton = new QPushButton();
	imageLabel = new QLabel(imageButton);
	imageLabel->setMaximumSize(50,50);
	imageLabel->setScaledContents(true);
	if(group->getImage() != "0")
	{
		imageLabel->setPixmap( group->getImage() );
		debug( "Group image path :: " + group->getImage() );
	}
	imageLabel->setMargin(5);
	imageButton->setMaximumSize(50,50);
	imageButton->setMinimumSize(50,50);
	titleLayout->addWidget(imageButton);
	titleLayout->addWidget(titre);
	doublonWidget = new DoublonWidget(kontacts, w, true);
	mainLayout = new QVBoxLayout;
	mainLayout->addLayout( titleLayout );
	mainLayout->addWidget( doublonWidget );
	buttonLayout = new QHBoxLayout;
	mAdd = new QPushButton(tr("Ajouter des kontacts"));
	mAdd->setMaximumSize(mAdd->sizeHint());
	buttonLayout->addWidget(mAdd);
	mMailAll = new QPushButton(tr("Envoyer un mail à tous"));
	mMailAll->setMaximumSize(mMailAll->sizeHint());
	buttonLayout->addWidget(mMailAll);
	mainLayout->addLayout(buttonLayout);
	this->setLayout( mainLayout );
	connect(mMailAll, SIGNAL( clicked() ), this, SLOT( mailAll() ) );
	connect(doublonWidget, SIGNAL( please(int) ), this, SLOT( pleaseTrt(int)));
	connect(mAdd, SIGNAL( clicked() ), this, SLOT( addK() ));
	connect(imageButton, SIGNAL( clicked() ), this, SLOT( changeImage() ) );
	connect(mW, SIGNAL( printRequest() ), this, SLOT( print() ) );
}
示例#6
0
文件: bankers.c 项目: 0x4849/cmput379
void runProcesses(int *allocationArray, int *workArray, int *maxArray, int *requestedResources, int *needArray, int *waitingQueue, int *maxAvailableResources, int *releaseResources,  int numProc, int numRes)
{

  int isAllZero;
  int offSet;
  int i, j, k, isSafeToAllocateRes;
  int requestedRandomAction;
  int requestRandomRes;
  int *tempWork;

  char reqGranted[100], reqNotGranted[100], curRequest[100];


  offSet = 0;
  checkIfDeadLock(waitingQueue, numProc);
  for (i=0; i < numProc; i++)
  {
    /* Let 0 = Do Nothing, 1 = Request Resources, 2 = Release Resources */
    /* Return random value [0,3) */
    
    if (waitingQueue[i] == 1)
    {
      /* If the process is currently in the waiting queue, then skip execution */
      continue;
    }

    requestedRandomAction = getRandomValue(0, 3);
    /* If we want to just continue execution, then go ahead and do so */
    if (requestedRandomAction == 0)
    {
      continue;
    }

    /* This will correspond to a resource release request */
    else if (requestedRandomAction == 2)
    {
      /* If all of our allocated resources are currently zero, and the
         process still wanted to release some resources, then we simply
         continue execution, and we skip this part.

         It is not really necessary -- because we could simply
         release 0 resources each time and then try to satisfy remaining
         requests on the waiting queue.

         So this here is open for interpretation. Would a process
         with zero resources allocated ever tell the operating system
         that it wishes to resource its resources? In my opinion, no,
         so that it is why I have chosen to skip execution here. */
        
      if (allResourcesAreZero(numRes, i * numRes, allocationArray))
      {
        continue;
      }
      else
      {
        offSet = i * numRes;
        j = 0;
        isAllZero = 1;
          
        while (j < numRes)
        {
          requestRandomRes = getRandomValue(0, allocationArray[offSet]+1);
          if (requestRandomRes)
          {
            isAllZero = 0;
          }
          releaseResources[j] = requestRandomRes;
          offSet++;
          j++;
        }
        /* Another situation completely open for interpretation.
           Here we are releasing 0 resources of each resource type.
           The professor told me that it is not valid to request 0
           resources of each type, so in my opinion, it is not valid to
           release all 0 resources of each type, so if the request involves
           all zero resources, then simply skip execution. */
        if (isAllZero)
        {
          continue;
        }

        printf("P%d has released ", i+1);
        printReleaseResources(releaseResources, numRes);
        releaseTheResources(releaseResources, allocationArray, workArray, i*numRes, numRes);

        /* After resources have been released, it is necessary to update
           the allocation, work, need arrays */
        makeInitialChangesToWorkAndNeed(numRes, i*numRes, allocationArray, requestedResources, maxArray, needArray, workArray);

        /* Try to satisfy all requests on the waiting queue since we have released
           resources */
        tryToSatisfyAllRequests(numRes, numProc, waitingQueue, requestedResources, allocationArray, workArray, needArray, maxArray, maxAvailableResources); 
      }

    }

    /* The requested action was to request resources, so this will start a chain of
       events that includes using the Banker's algorithm if needed to see if the
       system can remain in a safe state or not */
    else if (requestedRandomAction == 1)
    {

      offSet = i * numRes;
      j = 0;
      while (j < numRes)
      {
        requestRandomRes = getRandomValue(0, needArray[offSet]+1);
        requestedResources[offSet] = requestRandomRes;
        offSet++;
        j++;
      }


      /* All of the resources requested of each instance was 0.
         The professor told me that this request is not valid, so I am
         skippping execution here */
      
      if (allResourcesAreZero(numRes, i*numRes, requestedResources))
      {
        continue;
      }

      /* Print a snapshot of the system after the request has been made */
      printCurrentSnapshot(allocationArray, requestedResources, workArray, maxArray, needArray,waitingQueue, maxAvailableResources, numProc, numRes);

      sprintf(curRequest, "came from P%d", i+1);
      printRequest(numRes, requestedResources, i*numRes, curRequest); 
      printf("\n");
      offSet = i * numRes;
      
      /* Check to see if the system is in a safe state for giving the request or not */
      isSafeToAllocateRes = checkSafeState(workArray, needArray, maxArray, allocationArray, requestedResources, waitingQueue, numProc, numRes, offSet);

      if (isSafeToAllocateRes)
      {
        /* if it's safe to allocate the resource, then print snapshot and make the
           changes necessary to the given arrays */
        sprintf(reqGranted, "from P%d has been granted", i+1);
        printRequest(numRes, requestedResources, offSet, reqGranted); 
        makeInitialChangesToWorkAndNeed(numRes, offSet, allocationArray, requestedResources, maxArray, needArray, workArray);
        /* Remember to clear out requestedResources since request has been granted. */
        removeRequestedResources(numRes,requestedResources, offSet);

        /* print snapshot after request was OK'd */
        printCurrentSnapshot(allocationArray, requestedResources, workArray, maxArray, needArray,waitingQueue, maxAvailableResources, numProc, numRes);
          
      }
      else
      {
        /* Request not satisfied -- add the process to the waiting queue */
        sprintf(reqNotGranted, "from P%d cannot be satisfied, P%d is in waiting state", i+1, i+1);
        printRequest(numRes, requestedResources, offSet, reqNotGranted);
        waitingQueue[i] = 1;          
      }
       

    }

     
        
  }
}
示例#7
0
int main(int argc, char *argv[]){
    int option = 0, ecpPort = ECP_PORT + GN;
    //struct hostent *hostptr;
    struct sockaddr_in serveraddr, clientaddr;
    int fd, addrlen, ret, topicID, nread;
    char buffer[BUFFER_SIZE], awtString[AWT_STRING], awtesString[AWT_STRING], awiString[AWT_STRING];

    while ((option = getopt(argc, argv, "p:")) != -1){
        switch (option){
        case 'p':
            ecpPort = atoi (optarg);
            break;
        default:
            break;
        }
    }

    fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (fd==-1){
        fprintf(stderr, "Error creating UDP socket\n");
        exit(EXIT_FAILURE);
    }

    memset((void*)&serveraddr, (int)'\0', sizeof(serveraddr));
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = htonl(INADDR_ANY);
    serveraddr.sin_port = htons((unsigned short)ecpPort);

    ret = bind(fd, (struct sockaddr*)&serveraddr, sizeof(serveraddr));
    if(ret==-1){
        fprintf(stderr, "Error binding\n");
        exit(EXIT_FAILURE);
    }

    while(1){
        addrlen = sizeof(clientaddr);
        nread = recvfrom(fd, buffer, sizeof(buffer)+1, 0, (struct sockaddr*)&clientaddr, (unsigned*)&addrlen);
        if (nread==-1){
            fprintf(stderr, "Error receiving user request\n");
            exit(EXIT_FAILURE);
        }
        buffer[nread] = '\0';

        if (strncmp(buffer, "TQR", 3) == 0){
            printRequest(buffer, &clientaddr);
            TQR_command(awtString);
            ret = sendto(fd, awtString, strlen(awtString)+1, 0, (struct sockaddr*)&clientaddr, addrlen);
            if(ret==-1){
                fprintf(stderr, "Error sending reply to user\n");
                exit(EXIT_FAILURE);
            }
        }
        else if (strncmp(buffer, "TER", 3) == 0){
            printRequest(buffer, &clientaddr);
            topicID = buffer[TOPICID_INDEX]-'0';
            TER_command(awtesString, topicID);
            ret = sendto(fd, awtesString, strlen(awtesString)+1, 0, (struct sockaddr*)&clientaddr, addrlen);
            if(ret==-1){
                fprintf(stderr, "Error sending reply to user\n");
                exit(EXIT_FAILURE);
            }
        }
        else if(strncmp(buffer, "IQR", 3) == 0){
            printRequest(buffer, &clientaddr);
            IQR_command(buffer, awiString);
            ret = sendto(fd, awiString, strlen(awiString), 0, (struct sockaddr*)&clientaddr, addrlen);
            if(ret==-1){
                fprintf(stderr, "Error sending reply to user\n");
                exit(EXIT_FAILURE);
            }
        }
        else{
            printRequest(buffer, &clientaddr);
            ret = sendto(fd, "ERR\n", strlen("ERR\n")+1, 0, (struct sockaddr*)&clientaddr, addrlen);
            if(ret==-1){
                fprintf(stderr, "Error sending reply to user\n");
                exit(EXIT_FAILURE);
            }
        }
        memset(buffer, 0, strlen(buffer));
    }
    close(fd);

    exit(EXIT_SUCCESS);
}