Example #1
0
File: stdes.c Project: Swagg3r/CSE
// Reecriture de fprintf present dans la libc.
int fecriref(FICHIER* f, char* format, ...) {
	va_list ap;	//structure interne au compilateur pour savoir ou il en est.
	va_start(ap, format); //Il faut lui donner le dernier parametre connu avant les "..." a savoir format.

	int i = 0;
	while(*(format+i) != '\0') {
		if (*(format+i) == '%') {
			i++;
			switch(*(format+i)) {
				case 'c' : {
					int c = va_arg(ap, int);
					ecrire(&c, sizeof(char), 1, f);
					break;
				}
				case 'd' : {
					int d = va_arg(ap, int);
					char* chaine = conversion(d);
					ecrire(chaine, strlen(chaine), 1, f);
					break;
				}
				case 's' : {
					char* s = va_arg(ap, char*);
					ecrire(s, strlen(s), 1, f);
					break;
				}
			}
		} else { 
Example #2
0
File: test.c Project: Swagg3r/CSE
int main(int argc, char *argv[])
{
	FICHIER *f1;
	FICHIER *f2;
	char c;

	if (argc != 3)
		exit(-1);

	f1 = ouvrir (argv[1], 'L');
	if (f1 == NULL)
		exit (-1);
	
	f2 = ouvrir (argv[2], 'E');
	if (f2 == NULL)
		exit (-1);

	while (lire (&c, 1, 1, f1) == 1) {
		ecrire (&c, 1, 1, f2);
	}

	fermer (f1);
	fermer (f2);

	return 0;
}
bool MappeurAppareils::inserer(Appareil *appareil)
{
    const QString commande("INSERT INTO appareils\
                                (idType, idFabricant, idClient, description, motDePasse)\
                            VALUES\
                                (:idType, :idFabricant, :idClient, :description, :motDePasse)");
    const bool succes = ecrire(appareil, commande);
    appareil->setId(AideMappeurs::derniereInsertion());
    return succes;
}
bool MappeurAppareils::mettreAJour(const Appareil *appareil)
{
    const QString commande("UPDATE appareils\
                            SET\
                                description=:description,\
                                motDePasse=:motDePasse,\
                                idType=:idType,\
                                idFabricant=:idFabricant\
                            WHERE id=:idAppareil");
    const bool succes = ecrire(appareil, commande);
    return succes;
}
Example #5
0
/* main program. Creates the philosophers and the waiter and waits for termination of its children. */
void
dinner(int num_philo, int num_cycles)
{
  if (num_philo < 2 || num_cycles < 1)
  {
    ecrire("Parameters with impossible values\n");
    quitter(FAILURE);
  }
  int            *philos;       //to store the philosophers' pid
  int             waiter;
  int             my_prio = obtenir_priorite(obtenir_pid());
  int             child_prio = (my_prio == MAX_PRIORITY ? my_prio : my_prio + 1);       //let's give an lower priority to the children in order to minimize the number of preemptions before the start of the dinner.
  int             status;
  int             args[4] = { 0, 0, 0, 0 };

  philos = allouer(num_philo * sizeof(int));
  if (philos == NULL)
  {
    ecrire("Allouer philos failed\n");
    quitter(FAILURE);
  }

  int             i, j;
  ecrire("The dining philosophers. \nBon appétit !\n");
  // we need to spawn the waiter first
  args[0] = num_philo;
  waiter = fourchette(child_prio, "waiter", args);
  if (waiter < 1)
  {
    ecrire("An error occured. The program will stop.\n");
    quitter(FAILURE);
  }
  args[0] = waiter;             //the waiter's pid is a parameter of the philosophers
  args[2] = num_cycles;
  // spawns the philosophers
  for (i = 0; i < num_philo; i++)
  {
    args[1] = i;                //philosopher's id
    philos[i] = fourchette(child_prio, "philosopher", args);
    if (philos[i] < 1)
    {
      ecrire
        ("An error occured. Impossible to create the philosophers. The process will exit now.\n");
      //clean up
      for (j = 0; j < i; j++)
        tuer(philos[j], FAILURE);
      tuer(waiter, FAILURE);
      quitter(FAILURE);
    }
  }
  //everything's done, let's wait for the end 
  for (i = 0; i < num_philo; i++)
    attendre(philos[i], &status);
  //the waiter can stop
  envoyer_entier(waiter, END_OF_DINNER, 10);
  attendre(waiter, &status);
  ecrire("The dinner ends.\n");
  quitter(SUCCESS);
}
Example #6
0
// Ecrit dans le fichier les paramètres passés
int fecriref(FICHIER *f, char* format, ...) {
	if (f->mode != 'E') {
		return -1;
	}
	va_list va;
	va_start(va, format);
	int i;
	// Parcourt la chaine 'format' jusqu'à la fin
	for(i = 0 ; format[i] != '\0'; i++) {
		char c = format[i];
		// Si c'est un caractère spécial, on écrit ce qui est passé en paramètre
		if(c == '%') {
			i++;
			c = format[i];
			if(c == 'c') {
				char tmp = (char)va_arg(va, int);
				ecrire(&tmp, 1, 1, f);
			} else if (c == 's') {
Example #7
0
int partie2 (char* fichier1, char* fichier2){
	FICHIER *f1;
	FICHIER *f2;
	char c;

	f1 = ouvrir (fichier1, 'L');
	if (f1 == NULL)
		exit (-1);
	
	f2 = ouvrir (fichier2, 'E');
	if (f2 == NULL)
		exit (-1);

	while (lire (&c, 1, 1, f1) == 1) {
		ecrire (&c, 1, 1, f2);
	}

	fermer (f1);
	fermer (f2);

	return 0;
}
Example #8
0
void Serveur::readServeur()
{
        QString message=QString::fromUtf8(this->readAll());


	QString currentChan=tab->tabText(tab->currentIndex());

	if(message.startsWith("PING :"))
	{
		QStringList liste=message.split(" ");
		QString msg="PONG "+liste.at(1);
		sendData(msg);
	}
	else if(message.contains("Nickname is already in use."))
	{
        pseudo=pseudo+"_2";
		pseudo.remove("\r\n");
		sendData("NICK "+pseudo);
		emit pseudoChanged(pseudo);
        ecrire("-> Name changed to "+pseudo);
	}
        else if(updateUsers==true)
	{
		updateUsersList("",message);
	}

    QStringList list=message.split("\r\n");
        foreach(QString msg,list)
        {
            if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PRIVMSG ([a-zA-Z0-9\\#]+) :(.+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PRIVMSG ([a-zA-Z0-9\\#]+) :(.+)");
                QString msg2=msg;
                    ecrire(msg.replace(reg,"\\2 <b>&lt;\\1&gt;</b> \\3"),"",msg2.replace(reg,"\\2 <\\1> \\3"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ JOIN ([a-zA-Z0-9\\#]+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ JOIN ([a-zA-Z0-9\\#]+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"\\2 <i>-> \\1 join \\2</i><br />"),"",msg2.replace(reg,"-> \\1 join \\2"));
                updateUsersList(msg.replace(reg,"\\2"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PART ([a-zA-Z0-9\\#]+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PART ([a-zA-Z0-9\\#]+) :(.+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"\\2 <i>-> \\1 quit \\2 (\\3)</i><br />"),"",msg2.replace(reg,"-> \\1 quit \\2"));
                updateUsersList(msg.replace(reg,"\\2"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ QUIT (.+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ QUIT (.+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"\\2 <i>-> \\1 quit this server (\\2)</i><br />"),"",msg2.replace(reg,"-> \\1 left"));
                updateUsersList(msg.replace(reg,"\\2"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NICK :(.+)")))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NICK :(.+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"<i>\\1 is now called \\2</i><br />"),"",msg2.replace(reg,"-> \\1 is now called \\2"));
                updateUsersList(currentChan);
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ KICK ([a-zA-Z0-9\\#]+) ([a-zA-Z0-9]+) :(.+)")))
            { 
                QRegExp reg(":([a-zA-Z0-9]+)\\!~[a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ KICK ([a-zA-Z0-9\\#]+) ([a-zA-Z0-9]+) :(.+)");
                QString msg2=msg;
                ecrire(msg.replace(reg,"\\2 <i>-> \\1 kicked \\3 (\\4)</i><br />"),"",msg2.replace(reg,"-> \\1 quit \\3"));
                updateUsersList(msg.replace(reg,"\\2"));
            }
            else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NOTICE ([a-zA-Z0-9]+) :(.+)")))
            {
                if(conversations.contains(currentChan))
                {
                    QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NOTICE [a-zA-Z0-9]+ :(.+)");
                    ecrire(msg.replace(reg,"<b>[NOTICE] <i>\\1</i> : \\2 <br />"),currentChan);
                }
                else if(currentChan==serveur)
                {
                    QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NOTICE [a-zA-Z0-9]+ :(.+)");
                    ecrire(msg.replace(reg,"<b>[NOTICE] <i>\\1</i> : \\2 <br />"));
                }
            }
            else if(msg.contains("/MOTD command."))
            {
             joins();


            }



        }

        //}
}
Example #9
0
QString Serveur::parseCommande(QString comm,bool serveur)
{
    if(comm.startsWith("/"))
    {
        comm.remove(0,1);
        QString pref=comm.split(" ").first();
        QStringList args=comm.split(" ");
        args.removeFirst();
        QString destChan=tab->tabText(tab->currentIndex());
        QString msg=args.join(" ");

        if(pref=="me")
            return "PRIVMSG "+destChan+" ACTION " + msg + "";
        else if(pref=="msg")
            return "MSG "+destChan+" ACTION " + msg + "";
        else if(pref=="join")
        {
            join(msg);
            return " ";
        }
        else if(pref=="quit")
        {
            if(msg == "")
                return "QUIT "+msgQuit;
            else
                return "QUIT "+msg;
        }
        else if(pref=="part")
        {
            tab->removeTab(tab->currentIndex());

            if(msg == "")
            {
                if(msg.startsWith("#"))
                    destChan=msg.split(" ").first();

                if(msgQuit=="")
                    return "PART "+destChan+" using IrcLightClient";
                else
                    return "PART "+destChan+" "+msgQuit;
            }
            else
                return "PART "+destChan+" "+msg;

            conversations.remove(destChan);
        }
        else if(pref=="kick")
        {
            QStringList tableau=msg.split(" ");
            QString c1,c2,c3;
            if(tableau.count() > 0) c1=" "+tableau.first();
            else c1="";
            if(tableau.count() > 1) c2=" "+tableau.at(1);
            else c2="";
            if(tableau.count() > 2) c3=" "+tableau.at(2);
            else c3="";

            if(c1.startsWith("#"))
                return "KICK"+c1+c2+c3;
            else
                return "KICK "+destChan+c1+c2;
        }
        else if(pref=="update")
        {
            updateUsers=true;
            return "WHO "+destChan;
        }
        else if(pref=="ns")
        {
            return "NICKSERV "+msg;
        }
        else if(pref=="nick")
        {
            emit pseudoChanged(msg);
                        ecrire("-> Nickname changed to "+msg);
            return "NICK "+msg;
        }
        else if(pref=="msg")
        {
            return "MSG "+msg;
        }

        else
            return pref+" "+msg;
    }
    else if(!serveur)
	{
        QString destChan=tab->tabText(tab->currentIndex());
                if(comm.endsWith("<br />"))
                    comm=comm.remove(QRegExp("<br />$"));
                ecrire("<b>&lt;"+pseudo+"&gt;</b> "+comm,destChan);

        if(comm.startsWith(":"))
            comm.insert(0,":");

        return "PRIVMSG "+destChan+" "+comm.replace(" ","\t");
    }
	else
	{
		return "";
	}
}
Example #10
0
/**
 * Cette fonction est la boucle principale du programme.
 * Elle permet de rassembler toutes les autres fonctions dans un contenu reflétant
 * le fonctionnement du programme. Pour comprendre le fonctionnement d'un programme,
 * lire le main() devrait suffire.
 * Dans notre cas en revanche ce n'est pas tout à fait exact, car gtk implique
 * une execution évènementielle, c'est à dire une éxécution basée sur les
 * évènements. Le programme ne se lit donc plus du haut vers le bas, mais en
 * fonction des évènements liés à des fonctions dites de callback, dans le fichier
 * libGUI.c.
 */
int main(int argc, char ** argv)
{

    // Commençons par charger les préférences, si elles existent. On ouvre le fichier
    // en lecture pour charger la structure préférences :
    fichierPreferences = fopen(".olonoPrefs", "rb");
    if (fichierPreferences == NULL)
        erreur("Pas de fichier de préférences trouvé\n");
    else
    {
        // On lit 1 élément de donnée de longueur preferences depuis le fichier
        // fPreferences pour le stocker dans la variable prefs (de type preferences)
        fread(&prefs,sizeof(preferences),1,fichierPreferences);

        /// INIT 2 : Préférences globales (from file)
        couleurDepart = prefs.couleurDepart;
        allowIA       = prefs.allowIA;
        couleurIA     = prefs.couleurIA;
        affJouable    = prefs.affJouable;
        taillePlateau = prefs.taillePlateau;

        if (args.verbose)
            ecrire("Chargement de :\n\t couleurDepart: %d, allowIA      : %d\n\t couleurIA    : %d, taillePlateau: %d",couleurDepart,allowIA,couleurIA,taillePlateau);
    }



    /* On initialise les arguments à leur valeur par défaut */
    args.taillePlateau = 0;
    args.verbose       = 0;
    args.Tore          = 0;

    /* This is where the magic should happen | Attention, instant magique ... */
    argp_parse (&argp, argc, argv, 0, 0, &args);

    /// INIT 3 : Préférences globales (from)
    if (args.taillePlateau != 0)
        if (atoi((char*) args.taillePlateau) <= 25 && atoi((char*) args.taillePlateau) >= 4)
            taillePlateau = atoi((char*) args.taillePlateau);


    /// Les 3 priorités d'initialisation étant terminées, on peut désormais
    //  assigner la couleur de départ du jeton :
    jeton = couleurDepart;


/// ######################################################################## ///
/// ### On commence les choses sérieuses ici (cad le main) ################# ///
/// ######################################################################## ///

    gint    i=0,j=0,n=0;
    CASE    caseActuelle[625];

    wOlono = g_malloc(sizeof(window));

    plateau = createPlateau();
    initPlateau(plateau);
    tronc = initHistorique(plateau,couleurDepart);


/// ######################################################################## ///
/// ### On fait chauffer l'Interface Graphique ############################# ///
/// ######################################################################## ///
    GladeXML    *xml;

    /* Initialisation de la lib GTK+ */
    gtk_init(&argc, &argv);

    /* load the interface and complete it with the variable pieces */
    xml = glade_xml_new(DATADIR "/" GLADEDIR "/" GLADEFILE, NULL, NULL);

    /* connect the signals in the interface */
    glade_xml_signal_autoconnect(xml);

    /*    // timer up*/
    /*    wOlono->pIAClock = g_timer_new();*/
    /*    g_timer_start(wOlono->pIAClock);*/

    // get the main Window
    wOlono->pWindow     = glade_xml_get_widget(xml, "olonoWindow");
    gtk_window_set_title(GTK_WINDOW (wOlono->pWindow), "OloNO v" VERSION);

    // get checkBoxes, and set their values
    wOlono->pCheckAllowIA = glade_xml_get_widget(xml, "allowIA");
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (wOlono->pCheckAllowIA),allowIA);
    wOlono->pCheckiaIsBlack = glade_xml_get_widget(xml, "iaIsBlack");
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (wOlono->pCheckiaIsBlack),couleurIA);
    wOlono->pCheckAffJouable = glade_xml_get_widget(xml, "showPossibleMoves");
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (wOlono->pCheckAffJouable),affJouable);
    wOlono->pCheckCouleurDeb = glade_xml_get_widget(xml, "whiteStart");
    gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON (wOlono->pCheckCouleurDeb),!couleurDepart);

    // also get the spin button and set the default value :
    wOlono->pSpinTT = glade_xml_get_widget(xml, "taillePlateau");
    gtk_spin_button_set_value(GTK_SPIN_BUTTON (wOlono->pSpinTT),taillePlateau);

    // why not speak to the prefs window too ?
    wOlono->pPrefWindow = glade_xml_get_widget(xml, "olonoPreferences");

    // get the status bar :
    wOlono->pStatusBar  = glade_xml_get_widget(xml, "barreDesTaches");

    // creating context ids :
    wOlono->contextId01 = gtk_statusbar_get_context_id(GTK_STATUSBAR(wOlono->pStatusBar),
                          "MsgTour");
    wOlono->contextId02 = gtk_statusbar_get_context_id(GTK_STATUSBAR(wOlono->pStatusBar),
                          "MsgScore");

    // creating first blank message for contextId01 :
    gtk_statusbar_push (GTK_STATUSBAR (wOlono->pStatusBar),
                        GPOINTER_TO_INT(wOlono->contextId01),"Bienvenue - Youkoso");

    // On s'occupe de charger les images en mémoire :
    wOlono->imgVide     = gdk_pixbuf_new_from_file(DATADIR "/" IMGDIR "/" IMGVIDE,&wOlono->gerror);
    wOlono->imgBlanche  = gdk_pixbuf_new_from_file(DATADIR "/" IMGDIR "/" IMGBLANCHE,&wOlono->gerror);
    wOlono->imgNoire    = gdk_pixbuf_new_from_file(DATADIR "/" IMGDIR "/" IMGNOIRE,&wOlono->gerror);
    wOlono->imgJoker    = gdk_pixbuf_new_from_file(DATADIR "/" IMGDIR "/" IMGJOKER,&wOlono->gerror);

    // Puis on créé les dérivées transparentes :
    wOlono->imgTransBlanche = gdk_pixbuf_new_from_file(DATADIR "/" IMGDIR "/" IMGTBLANCHE,&wOlono->gerror);
    wOlono->imgTransNoire   = gdk_pixbuf_new_from_file(DATADIR "/" IMGDIR "/" IMGTNOIRE,&wOlono->gerror);


    // set the plateau.
    wOlono->pPlateau    = gtk_table_new(taillePlateau,taillePlateau,TRUE);

    for (i=0;i<taillePlateau;i++)
    {
        for (j=0;j<taillePlateau;j++)
        {
            n=i*taillePlateau+j;
            wOlono->pImage[n] = gtk_image_new();
            wOlono->pEvent[n] = gtk_event_box_new ();
            gtk_container_add (GTK_CONTAINER (wOlono->pEvent[n]), wOlono->pImage[n]);

            // Important : On place le gtk_event_box au dessus sinon on peut pas
            // recevoir des évènements, puisqu'il est caché par l'image.
            gtk_event_box_set_above_child (GTK_EVENT_BOX (wOlono->pEvent[n]),1);

            // On rempli caseActuelle :
            caseActuelle[n].x = i;
            caseActuelle[n].y = j;

            // On connecte chaque signal à la fonction callback :
            g_signal_connect (G_OBJECT (wOlono->pEvent[n]),
                              "button_press_event",
                              G_CALLBACK (on_case_clic),
                              &caseActuelle[n]);

            gtk_table_attach_defaults (GTK_TABLE (wOlono->pPlateau),
                                       wOlono->pEvent[n], i, i+1, j, j+1);
        }
    }

    /* Rafraichit le plateau (fait concorder celui en mémoire et celui affiché) */
    refreshBoard(plateau);

    wOlono->pContainer = glade_xml_get_widget(xml, "cadreAspect");
    gtk_container_add(GTK_CONTAINER(wOlono->pContainer), wOlono->pPlateau);

    /* For all the abandonned widgets ie plateau */
    gtk_widget_show_all (wOlono->pPlateau);

    /* start the event loop */
    gtk_main();

    return 0;
}
Example #11
0
void Serveur::action(std::stringstream &fichier,std::string &ligne, std::string &arg)
{
    std::string destination;
    if(ligne == "redemarrer")
    {
        (*running) = false;
        std::string tmp = "start prePatcher.exe" + arg + " &";//pour linux, remplacer "start " par "./"
        system(tmp.c_str());
        return;
    }
    std::getline(fichier, destination);
    if(destination.find("./") != -1)
	{
	    std::cout << destination << std::endl;
        param->setMessage(4);
		sf::Sleep(3);
		exit(1);
    }
    if(ligne == "nouveau dossier")
    {
        //uniquement pour windows je crois
        CreateDirectory(destination.c_str(),NULL);
        //pour Linux? mkdir(destination.c_str());
    }
    else if(ligne == "supprimer dossier")
    {
        //Le répertoire doit être vide
        destination = "rmdir " + destination;
        system(destination.c_str());
        //rmdir(destination.c_str());
    }
    else if(ligne == "supprimer dossier Patcher")
    {
        arg += " supprimer_dossier " + destination;
    }
    else if(ligne == "supprimer")
    {
        remove(destination.c_str());
    }
    else if(ligne == "supprimer Patcher")
    {
        arg += " supprimer " + destination;
    }
    else if(ligne == "deplacer")
    {
        std::string tmp;
        std::getline(fichier, tmp);
        MoveFile(destination.c_str(), tmp.c_str());
    }
    else if(ligne == "deplacer Patcher")
    {
        std::string tmp;
        std::getline(fichier, tmp);
        arg += " deplacer " + destination + " " + tmp;
    }
    else if(ligne == "Telecharger" || ligne == "Telecharger Patcher")
    {
        std::string tmp;
        std::getline(fichier, tmp);
        connexion(destination);
        if(ligne == "Telecharger patcher")
        {
            tmp += "_bis";
            arg += " Patcher " + tmp;
        }
        std::ofstream ecrire(tmp.c_str());
        ecrire << Page.GetBody();
		ecrire.close();
    }
}
Example #12
0
void
waiter(int num_philo)
{
  int             i, j, code, philo_pid, philo_id, in, do_packing, end = 0;
  int            *forks, *philos_pid;   //the waiter knows the status of each fork. Will contain FORK_TAKEN or FORK_FREE
  message_t       temp, recv, *buffer;  //the waiter will need to buffer the requests that can't be satisfied when he gets the message. At most num_philo-1 messages can be buffered at the same time. One more and it's a deadlock. 
  int             forks_taken = 0;      //counts the number of forks taken

  //let's allocate the arrays
  forks = allouer(num_philo * sizeof(int));
  if (forks == NULL)
  {
    ecrire("Allouer forks failed\n");
    quitter(FAILURE);
  }
  philos_pid = allouer(num_philo * sizeof(int));
  if (philos_pid == NULL)
  {
    ecrire("Allouer philos_pid failed\n");
    quitter(FAILURE);
  }
  buffer = allouer((num_philo - 1) * sizeof(message_t));
  if (buffer == NULL)
  {
    ecrire("Allouer buffer failed\n");
    quitter(FAILURE);
  }

  //we mark the forks as being free
  for (i = 0; i < num_philo; i++)
  {
    forks[i] = FORK_FREE;
  }

  //first, each philosopher sends its philo_id (NOT its pid) to the waiter
  for (i = 0; i < num_philo; i++)
  {
    recevoir_premier(&recv);
    philo_id = message_get_int_value(recv);
    philo_pid = message_get_from(recv);
    liberer_message(recv);
    philos_pid[philo_id] = philo_pid;
  }
  ecrire("Waiter: I have everything I need, let's go !\n");
  //starts the dinner
  for (i = 0; i < num_philo; i++)
    envoyer_entier(philos_pid[i], GO_FOR_IT, 10);

  in = 0;
  while (!end)
  {
    //the waiter loops until it receives the order to stop
    recevoir_premier(&recv);
    code = message_get_int_value(recv);
    philo_pid = message_get_from(recv);
    philo_id = get_philo_id(philo_pid, philos_pid, num_philo);
    switch (code)
    {
    case WANT_LEFT_FORK:
      if (!left_fork(philo_id, philo_pid, forks, &forks_taken, num_philo))
      {
        //fork taken or only one fork left. In the last case, it can only be taken by a philosopher who already has a fork. Since the left forks are requested first, this is not the case here. We put the request in the buffer
        buffer[in] = recv;
        in++;
      }
      else
        liberer_message(recv);
      break;
    case WANT_RIGHT_FORK:
      if (!right_fork
          ((philo_id + 1) % num_philo, philo_pid, forks, &forks_taken))
      {
        buffer[in] = recv;
        in++;
      }
      else
        liberer_message(recv);
      break;
    case PUT_FORKS_BACK:
      liberer_message(recv);
      forks[philo_id] = FORK_FREE;
      forks[(philo_id + 1) % num_philo] = FORK_FREE;
      forks_taken -= 2;
      //look if some of the buffered requests can be satisfied now
      for (i = 0; i < in; i++)
      {
        do_packing = 0;
        temp = buffer[i];
        code = message_get_int_value(temp);
        philo_pid = message_get_from(temp);
        philo_id = get_philo_id(philo_pid, philos_pid, num_philo);
        if (code == WANT_LEFT_FORK)
        {
          if (left_fork(philo_id, philo_pid, forks, &forks_taken, num_philo))
            //this request has been satisfied
            do_packing = 1;
        }
        else
          if (right_fork
              ((philo_id + 1) % num_philo, philo_pid, forks, &forks_taken))
          do_packing = 1;
        if (do_packing)
        {
          liberer_message(temp);
          //the request number i has been satisfied, let's pack the array
          for (j = i + 1; j < in; j++)
            buffer[j - 1] = buffer[j];
          in--;
          i--;
        }
      }
      break;
    case END_OF_DINNER:
      end = 1;
      liberer_message(recv);
      break;
    }
  }
}
Example #13
0
/* An average philosopher: thinking, eating, thinking, eating and so on. What a livelocked mind ! */
void
philosopher(int waiter_pid, int philo_id, int num_cycles)
{
  int             m_w = 4000 - philo_id, m_z = philo_id + 2000; //initializers for random numbers generation
  int             count = 0;    //each philosopher does num_cycles cycles before exiting
  int             my_pid = obtenir_pid();
  char            s[MAX_STRING], buf[4];
  message_t       mess;

  itoa(my_pid, buf, 4);

  //each philosopher gives its philo_id to the waiter. Those id represent the id of the forks
  strncpy(s, "Process ", MAX_STRING);
  strncat(s, buf, MAX_STRING - strlen(s));
  strncat(s, " is sending its id to the waiter\n", MAX_STRING - strlen(s));
  ecrire(s);
  envoyer_entier(waiter_pid, philo_id, 10);
  //wait until the waiter says the show can begin
  if (recevoir_de_delai(waiter_pid, &mess, 1000) != SUCCESS)
  {
    ecrire("The waiter took too long to answer. Dinner canceled\n");
    quitter(FAILURE);
  }
  liberer_message(mess);
  strncpy(s, "Process ", MAX_STRING);
  strncat(s, buf, MAX_STRING - strlen(s));
  strncat(s, " starts the dinner\n", MAX_STRING - strlen(s));
  ecrire(s);

  while (count < num_cycles)
  {
    strncpy(s, "Process ", MAX_STRING);
    strncat(s, buf, MAX_STRING - strlen(s));
    strncat(s, " is thinking\n", MAX_STRING - strlen(s));
    ecrire(s);
    retarder(my_pid, random(&m_w, &m_z) % 5000);
    strncpy(s, "Process ", MAX_STRING);
    strncat(s, buf, MAX_STRING - strlen(s));
    strncat(s, " is trying to get its left fork\n", MAX_STRING - strlen(s));
    ecrire(s);
    if (envoyer_entier(waiter_pid, WANT_LEFT_FORK, 10) != SUCCESS)
    {
      ecrire("Envoyer_entier failed\n");
      quitter(FAILURE);
    }
    recevoir_de(waiter_pid, &mess);
    liberer_message(mess);      //the content of a message from the waiter is always GO_FOR_IT
    strncpy(s, "Process ", MAX_STRING);
    strncat(s, buf, MAX_STRING - strlen(s));
    strncat(s, " is trying to get its right fork\n", MAX_STRING - strlen(s));
    ecrire(s);
    if (envoyer_entier(waiter_pid, WANT_RIGHT_FORK, 10) != SUCCESS)
    {
      ecrire("Envoyer_entier failed\n");
      quitter(FAILURE);
    }
    recevoir_de(waiter_pid, &mess);
    liberer_message(mess);
    strncpy(s, "Process ", MAX_STRING);
    strncat(s, buf, MAX_STRING - strlen(s));
    strncat(s, " is eating\n", MAX_STRING - strlen(s));
    ecrire(s);
    retarder(my_pid, random(&m_w, &m_z) % 5000);
    strncpy(s, "Process ", MAX_STRING);
    strncat(s, buf, MAX_STRING - strlen(s));
    strncat(s, " puts its forks back\n", MAX_STRING - strlen(s));
    ecrire(s);
    envoyer_entier(waiter_pid, PUT_FORKS_BACK, 10);
    count++;
  }
  strncpy(s, "Process ", MAX_STRING);
  strncat(s, buf, MAX_STRING - strlen(s));
  strncat(s, ", thanks for the food !\n", MAX_STRING - strlen(s));
  ecrire(s);
}
Example #14
0
int main(int argc , char **argv)
{
	unsigned int i, taille, op;
	char *data;
	struct stat s;
	FILE * f= NULL;
	unsigned char cle[16];
	unsigned char nonce[16];	
	char fichier[50];
	
	printf("\n");
	//test des arguents et analyse
	if(argc >5 || argc <4)
	{
		printf("-----------Utilisation----------------\n\n");
		printf(" %s F O C [N]\n",argv[0]);
		
		printf("F : le  fichier à chiffrer ou à déchiffrer\n");
		printf("O : l'opération voulue (1 pour chiffrer et 2 pour déchiffrer)\n");
		printf("C : le  fichier contenant la cle de (dé)chiffrement\n");
		printf("N : Dans le cas d'un déchiffrement (2), c'est le  fichier contenant la nonce\n");
		
		printf("\n");
		exit(EXIT_FAILURE);
		
	}
	
	
	
	f = fopen(argv[3],"rb");
	
	if(f == NULL)
		erreur("Ouverture du fichier devant contenir la cle");
	else if(fread(cle,1,16,f)!=16)
		erreur("Lecture dans le fichier contenant la cle de chiffrement / Contenu");
	
	op = atoi(argv[2]);
	
	if(op == 1)//préparation pour le chiffrement
	{
		if(argc != 4)
			erreur("Le nombre d'argument n'est pas compatible avec l'opération demandée");
		
		
		srand(time(NULL));
		for(i=0; i< 16; i++)
			nonce[i] = (unsigned char)rand();
		
		f = fopen("nonce.txt","wb");
		if(f == NULL)
			erreur("Création du fichier qui contiendra la nonce");
		if(fwrite(nonce,1,16,f) != 16)
			erreur("Ecriture dans le fichier qui contiendra la nonce");
		fclose(f);
		
	}
	else if(op == 2)//préparation pour le déchiffrement
	{
		if(argc != 5)
			erreur("Le nombre d'argument n'est pas compatible avec l'opération demandée");
		
		f = fopen(argv[4],"rb");
		if(f == NULL) 
			erreur("Ouverture du fichier  contenant la nonce");
		if(fread(nonce,1,16,f)!=16)
			erreur("Lecture dans le fichier contenant la nonce / Contenu");
		fclose(f);
		
	}
        
        //on récupère des information sur le fichier dont sa taille
	if(stat(argv[1],&s)==-1)
	erreur("Echec: Impossible de déterminer la taille du fichier ");
	
	taille = s.st_size + 10;
	
	if(taille == 1)//fichier vide
		erreur("Echec: Ce fichier est vide\n");
		
	data = malloc(taille*sizeof(char));
	if(data == NULL)
		erreur("Allocation mémoire pour la chaine devant contenir le fichier");
	
	//on récupère le fichier à chiffrer ou déchiffrer, effectue
	// l'opération et le stock dans un fichier dédié
	lire(argv[1],data,taille);
	chiffrement_AES_ModeCompteur(data,taille,nonce, cle);
	if(creation_fichier(argv[1],op,fichier)== 1)
		ecrire(data,taille,argv[1]);
	else
		ecrire(data,taille,fichier);
	
	//succes de l'opération
	if(op == 1)
	{
		printf("fin du chiffrement\n");
		printf("vous trouverez le chiffré dans %s ou dans le source pour le \".png\"\n",fichier);
		printf("vous trouverez la nonce dans le fichier nonce.txt\n");
	}
	else
	{
		printf("fin du déchiffrement\n");
		printf("vous trouverez le déchiffré dans %s ou dans le source pour .png\n",fichier);
	}
	
	printf("\n");
	exit(EXIT_SUCCESS);
}
Example #15
0
void Serveur::readServeur()
{
    QString message=QString::fromUtf8(this->readAll());

    QString currentChan=tab->tabText(tab->currentIndex());

    if(message.startsWith("PING :"))
    {
        QStringList liste=message.split(" ");
        QString msg="PONG "+liste.at(1);
        sendData(msg);
    }
    else if(message.contains("Nickname is already in use."))
    {
        pseudo=pseudo+"_2";
        pseudo.remove("\r\n");
        sendData("NICK "+pseudo);
        emit pseudoChanged(pseudo);
        ecrire("-> Name changed to "+pseudo);
    }
    else if(updateUsers==true)
    {
        updateUsersList("",message);
    }

    QStringList list=message.split("\r\n");
    foreach(QString msg,list)
    {
        if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PRIVMSG ([a-zA-Z0-9\\#]+) :(.+)")))
        {
            QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PRIVMSG ([a-zA-Z0-9\\#]+) :(.+)");
            QString msg2=msg;
            ecrire(msg.replace(reg,"\\2 <b>&lt;\\1&gt;</b> \\3"),"",msg2.replace(reg,"\\2 <\\1> \\3"));
        }
        else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ JOIN ([a-zA-Z0-9\\#]+)")))
        {
            QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ JOIN ([a-zA-Z0-9\\#]+)");
            QString msg2=msg;
            ecrire(msg.replace(reg,"\\2 <i>-> \\1 join \\2</i><br />"),"",msg2.replace(reg,"-> \\1 join \\2"));
            updateUsersList(msg.replace(reg,"\\2"));
        }
        else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PART ([a-zA-Z0-9\\#]+)")))
        {
            QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ PART ([a-zA-Z0-9\\#]+) :(.+)");
            QString msg2=msg;
            ecrire(msg.replace(reg,"\\2 <i>-> \\1 quit \\2 (\\3)</i><br />"),"",msg2.replace(reg,"-> \\1 quit \\2"));
            updateUsersList(msg.replace(reg,"\\2"));
        }
        else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ QUIT (.+)")))
        {
            QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ QUIT (.+)");
            QString msg2=msg;
            ecrire(msg.replace(reg,"\\2 <i>-> \\1 quit this server (\\2)</i><br />"),"",msg2.replace(reg,"-> \\1 left"));
            updateUsersList(msg.replace(reg,"\\2"));
        }
        else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NICK :(.+)")))
        {
            QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NICK :(.+)");
            QString msg2=msg;
            ecrire(msg.replace(reg,"<i>\\1 is now called \\2</i><br />"),"",msg2.replace(reg,"-> \\1 is now called \\2"));
            updateUsersList(currentChan);
        }
        else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ KICK ([a-zA-Z0-9\\#]+) ([a-zA-Z0-9]+) :(.+)")))
        { 
            QRegExp reg(":([a-zA-Z0-9]+)\\!~[a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ KICK ([a-zA-Z0-9\\#]+) ([a-zA-Z0-9]+) :(.+)");
            QString msg2=msg;
            ecrire(msg.replace(reg,"\\2 <i>-> \\1 kicked \\3 (\\4)</i><br />"),"",msg2.replace(reg,"-> \\1 quit \\3"));
            updateUsersList(msg.replace(reg,"\\2"));
        }
        else if(msg.contains(QRegExp(":([a-zA-Z0-9]+)\\![a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NOTICE ([a-zA-Z0-9]+) :(.+)")))
        {
            if(conversations.contains(currentChan))
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NOTICE [a-zA-Z0-9]+ :(.+)");
                ecrire(msg.replace(reg,"<b>[NOTICE] <i>\\1</i> : \\2 <br />"),currentChan);
            }
            else if(currentChan==serveur)
            {
                QRegExp reg(":([a-zA-Z0-9]+)\\![~a-zA-Z0-9]+@[a-zA-Z0-9\\/\\.-]+ NOTICE [a-zA-Z0-9]+ :(.+)");
                ecrire(msg.replace(reg,"<b>[NOTICE] <i>\\1</i> : \\2 <br />"));
            }
        }
        else if(msg.contains("/MOTD command."))
        {
            joins();
        }
        else if(msg.contains(QRegExp("= ([a-zA-Z0-9\\#]+) :")))
        {

            QStringList msg3 = msg.split("= ");
            QStringList msg4 = msg3[1].split(" :");
            updateUsersList(msg4[0],msg);
        }
        else
        {
            QString trimmedMsg = msg.trimmed();
            QStringList splitMsg = trimmedMsg.split(" ");
            if((splitMsg.size() > 7 && (splitMsg.at(3)+splitMsg.at(4)+splitMsg.at(5)+splitMsg.at(6)+splitMsg.at(7)).toStdString() == "#dopecoin:Endof/NAMESlist.") ||
                (splitMsg.size() > 7 && (splitMsg.at(3)+splitMsg.at(4)+splitMsg.at(5)+splitMsg.at(6)+splitMsg.at(7)).toStdString() == "#dopecoin:Endof/WHOlist.") ||
                (splitMsg.size() > 1 && splitMsg.at(0).toStdString() == "PING"))
                return;
            ecrire(trimmedMsg, QString::fromStdString("Console/PM"));
        }
    }
}
bool MappeurAppareils::supprimer(const Appareil *appareil)
{
    const QString commande("DELETE FROM appareils WHERE id=:idAppareil");
    const bool succes = ecrire(appareil, commande);
    return succes;
}