Beispiel #1
0
int main(char argc,char ** argv)
{
  if(argc < 2)
  {
    printf("Incorrect Arguments \n");
    printf("Correct Format - Enter 1 for Regular Round Robin Scheduling 2 for priority Round Robin Scheduling\n");
    exit(0);
  }
  PROC* readyQueue[50];							//queqe containing the list of all processess
  PROC* ProcessList[50];						//processess in the ready queue
  int terminated=0;								//number of terminated processess
  int type = atoi(argv[1]);						//type of the scheduler 
  pid_t main_PID = getpid();					//PID of the scheduler
  int mid,read,rc,num_msg,k;
  key_t key;
  MESSAGE msg;
  struct msqid_ds msglist;
  struct sigaction action;						

  action.sa_flags = SA_SIGINFO;					
  action.sa_sigaction = &toIO;					

  sigaction(SIGUSR1,&action,NULL);
  signal(SIGTERM,terminate);

  key = ftok(".",'V');
  if((mid = msgget(key, IPC_CREAT | 0660))<0)
	{
	printf("Error Creating message queue\n");
	exit(-1);
	}

	msgctl(mid, IPC_RMID, NULL);

	if((mid = msgget(key, IPC_CREAT | 0660))<0){
            printf("Error Creating Message Queue\n");
            exit(-1);
            }

  while(1)
  {
  	//printf("Entered outer while loop");
  	rc = msgctl(mid,IPC_STAT,&msglist);                      //sense the message queue
  	num_msg = msglist.msg_qnum;								//get the number of message
  	if(num_msg > 0)											
  	{
  		for(k=0;k<num_msg;++k)
  		{
  			if(msgrcv(mid,&msg, sizeof(msg.message),FROMPROCESS,0) < 0)
  			{
  				error("msgrcv");
  			}
  			if(strcmp(msg.message,"BEGI") == 0)
  			{													//if the process is coming for the first time
  				PROC * P = malloc (sizeof(PROC));				
  				P->index = count;								//store the index of the process
  				count++;											
  				P->PID = msg.PID;								//set the PID of process
  				//if its RRR then set the priority to 1 for all process
  				if(type == 1) P->priority=1;					
  				else
  					P->priority = msg.priority;
  				msg.from = FROMSCHEDULER;
  				msg.PID=main_PID;
  				strcpy(msg.message,"REC");
  				if(msgsnd(mid, &msg, sizeof(msg.message), 0)<0)
  				{	
                   error("msgsnd");
          }

                 P->arrival_time=time(NULL);
                 P->waiting_time=0;
                 P->turnaround_time=0;
                 P->response_time=0;
                 P->has_response=0;

                 printf("Process P %d , PID = %d arrived\n",P->index,P->PID);
                 P->inRQ=timenow();
                 ProcessList[P->index]=P;
                 push(P,readyQueue);              
  			}
  			else
  				if(!strcmp(msg.message,"IO"))
  				{
  					 PROC * P = malloc (sizeof(PROC));
                     int j=0;
                     for(j=0;j<count;j++)
                     {
                        if (ProcessList[j]->PID==msg.PID)
                           {
                        		P=ProcessList[j];
                     	      	break;
                            }
                      }

                        printf("%d : Process P%d , PID = %d returned from IO\n",(int)time(NULL),P->index,P->PID);
                        P->inRQ=timenow();
                        push(P,readyQueue);             

  				}
  		}
  	}
  	if(empty(readyQueue) == 0)     
             {
             	//printf("RQ not empty condition\n");
                       int in_io=0;
                        int q=0;
                       PROC * P = pop(readyQueue);            

                       struct timeval cur=timenow();
                       struct timeval rqt=(P->inRQ);
                       unsigned long tv= (cur.tv_sec-rqt.tv_sec) + 1000000*(cur.tv_usec-rqt.tv_usec);
                       P->waiting_time += tv;
                       if(P->has_response==0)			//setting the response flag to 1 after first IO operation
                       {							
                             P->response_time=P->waiting_time;
                             P->has_response=1;
                       }
                       kill(P->PID,SIGCONT);

                	   //printf("Process P %d is running\n",P->index);

                    for(q=0;q<TIME_QUANTA;q++)
                    {
                          if(ioPID==P->PID)
                          {
                                 ProcessList[P->index]=P;

                                 printf("%d  : Process P%d , PID = %d requesting I/O\n",(int)time(NULL),P->index,ioPID);
                                 ioPID=-1;
                                 in_io=1;
                                 break;
                          }

                          if(term_flag==1)
                          {
                                ProcessList[P->index]=P;
                                P->turnaround_time=time(NULL)-(P->arrival_time);
                                printf("%d  : Process P%d , PID = %d Terminated\n",(int)time(NULL),P->index,P->PID);
                                term_flag=0;
                                terminated++;
                                break;
                          }

                    }

                    if(terminated==count) break;     

                    

             }
  }
   FILE * fp;
        int file=atoi(argv[1]);
        if(file==1)       fp=fopen("RR_Stats","w");
        else fp=fopen("P_RR_Stats","w");
        time_t avg_w=0,avg_t=0,avg_r=0;
        int l=0;
        for(l=0;l<count;l++)
        {
             fprintf(fp,"Process P%d\n Waiting Time(microsec): %lu\nTurnaround Time (s): %d Response Time(microsec): %d\n\n",l,ProcessList[l]->waiting_time,(int)ProcessList[l]->turnaround_time,(int)ProcessList[l]->response_time);
             avg_w += ProcessList[l]->waiting_time;
             avg_t += ProcessList[l]->turnaround_time;
             avg_r += ProcessList[l]->response_time;
        }
        avg_w/=count;
        avg_t/=count;
        avg_r/=count;

        fprintf(fp,"Average\n Avg Waiting Time(microsec): %lu\nTurnaround Time (s): %d\nResponse Time(microsec): %d\n",avg_w,(int)avg_t,(int)avg_r);
        printf("\nFinished\n");
      fclose(fp);
       return 0;
}
int main(){
	int i, found, tested, exist;	//tested to record the total amount of tested number of terminated computing processes

	struct shmid_ds ds;
	msg_t snd, rcv;
	sigset_t mask;
	struct sigaction action;
	
	sigemptyset(&mask);
	sigaddset(&mask, SIGINT);
	sigaddset(&mask, SIGHUP);
	sigaddset(&mask, SIGQUIT);
	action.sa_mask= mask;
	action.sa_flags= 0;
	action.sa_handler= handler;
	sigaction(SIGINT, &action, NULL);
	sigaction(SIGQUIT, &action, NULL);
	sigaction(SIGHUP, &action, NULL);

	found= 0;
	tested= 0;
	
	bit[0]=1;
	for(i=1; i<8; i++){
		bit[i]= bit[i-1]<<1;
	}

	printf("**********************************\nmanage process  %d begins:\n", getpid());
	// create and attach shared memory
	if((shmid= shmget(KEY, sizeof(seg_t), IPC_CREAT|0666))==-1){
		perror("shmget");
		exit(EXIT_FAILURE);
	}
	printf("shmid: %d size: %ld\n", shmid, sizeof(seg_t));
	if((seg= (seg_t*)shmat(shmid, 0, 0))==(seg_t*)-1){
		perror("shmat");
		exit(EXIT_FAILURE);
	}
	shmctl(shmid, IPC_STAT, &ds);	
	printf("nattch: %d\n", (int)ds.shm_nattch);
	memset(seg, 0, sizeof(seg_t));
	
	// get message queue, create if not exists
	if((msqid= msgget(KEY, IPC_CREAT|0666))== -1){
		perror("msgget");
		exit(EXIT_FAILURE);
	}
	printf("message queue %d created\n*******************************\n", msqid);

	while(1){		
		if(msgrcv(msqid, &rcv, sizeof(msg_content), MANAGE_PORT, 0)==-1){
			perror("msgrcv");	
			exit(EXIT_FAILURE);
		}

		if(rcv.mtext.type== getent){
			printf("get a msg for entry number\n");
		 
			for(i=0; i<NUM_PROC; i++){
				if(seg->proc[i].pid== 0){		
					seg->proc[i].pid= snd.mtarget= rcv.mtext.sender;
					snd.mtext.type= getent;
					snd.mtext.data.entry= i;
					snd.mtext.sender= getpid();
					printf("%dth entry pid: %d\n", i, seg->proc[i].pid);
					if(msgsnd(msqid, &snd, sizeof(msg_content), 0)==-1){
						perror("msgsnd");
						exit(1);
					}
					
					break;
				}
			}
			if(i== NUM_PROC){
				perror("number of computing processes more than limit");
				exit(EXIT_FAILURE);
			}
			printf("----------------------------------\n");
		}else if(rcv.mtext.type== pfnum){
			//manage update perfect numbers
			exist= 0;
			for(i=0; i< found; i++){
				if(seg->pf[i]==rcv.mtext.data.num){
					exist= 1;
					break;
				}
			}
			if(exist==0){
				seg->pf[found++]= rcv.mtext.data.num;
			}
			printf("get a msg for perfect number: %d\n", rcv.mtext.data.num);
			printf("total found %d\n----------------------------------\n", found);
		}else if(rcv.mtext.type== mng_pid ){
		 	printf("get a msg for manage pid\n");
			snd.mtarget= rcv.mtext.sender;
			snd.mtext.type= mng_pid;
			snd.mtext.data.pid= getpid();
			snd.mtext.sender= getpid();
			if(msgsnd(msqid, &snd, sizeof(msg_content), 0)==-1){
				perror("msgsnd");
				exit(1);
			}
			printf("----------------------------------\n");
		}else if (rcv.mtext.type== end){
			/* replace these three lines with following commented if requiring manage to clear pid
			printf("get a msg for termination from compute process %d that tested %d numbers\n", rcv.mtext.sender, seg->proc[rcv.mtext.data.entry].tested);
			tested+= seg->proc[rcv.mtext.data.entry].tested; 
			memset(&seg->proc[rcv.mtext.data.entry], 0, sizeof(proc_t));*/
			
			printf("get a msg for termination from compute process %d that tested %d numbers\n", rcv.mtext.sender, rcv.mtext.data.num);
			tested+= rcv.mtext.data.num;
			for(i=0; i<NUM_PROC;i++){
				if(rcv.mtext.sender==seg->proc[i].pid){
					seg->proc[i].pid= 0;
					break;
				}
			}
			/**/
			printf("----------------------------------\n");
		}else if(rcv.mtext.type== report_test){
			printf("get a msg for reporting tested number\n");
			snd.mtarget= rcv.mtext.sender;
			snd.mtext.type= report_test;
			snd.mtext.sender= getpid();
			int t=0;
			for(i=0; i<NUM_PROC; i++){
				if(seg->proc[i].pid!=0){
					t+= seg->proc[i].tested;
				}
			}
			snd.mtext.data.num= tested + t;
			printf("tested:%d\n",snd.mtext.data.num);
			if(msgsnd(msqid, &snd, sizeof(msg_content), 0)==-1){
				perror("msgsnd");
				exit(1);
			}
			printf("----------------------------------\n");
		}else{
			fprintf(stderr, "unexpected message type\n");	
			exit(EXIT_FAILURE);
		}
	}

	return 0;
}
Beispiel #3
0
int main(){
	printf("Serwer uruchomiony pomyslnie!\n");
	buf = malloc(sizeof(struct mybuf));
	stolik = malloc(TBLS * sizeof(struct stoliki));
	gracz = malloc(MAX_PLYRS * sizeof(struct gracze));

	czyscPoczatek(gracz, stolik);


	int k;
	for(k=0;k<TBLS;k++){
		stolik[k].zajete=0;
	}
	for(k=0;k<MAX_PLYRS;k++){
		gracz[k].stolik=0;
	}

	int N = MAX_PLYRS;

	int msgSend = msgget(1234, IPC_CREAT|0600);
	if(msgSend==-1){
		perror("Utworzenie kol. kom. wych.");
		exit(1);
	}

	int msgRcv = msgget(4321, IPC_CREAT|0600);
	if(msgRcv==-1){
		perror("Utworzenie kol. kom. przych.");
		exit(1);
	}

	int quit=0;
	while(1)
	{

		//dodawanie uzytkownika do tymczasowej bazy danych
		if(msgrcv(msgRcv, buf, (sizeof(struct mybuf)-sizeof(long)), LOGIN ,IPC_NOWAIT) != -1){ //dodawanie graczy; IPC_NOWAIT sprawia ze nie nie ma zawiechy na komunikat
			buf->mtype = P_INFO;
			if(liczG < N){
				int pom = getSize(buf->val);
				if(pom>30){
					printf("%s ma wiecej niz 30 znakow\n");
					clearTab(buf->val, MAX);
					strcpy(buf->val, "Login ma miec max 30 znakow!\n");
				}
				else{
					strcpy(gracz[liczG].login, buf->val);
					gracz[liczG].stolik = 0;
					printf("%s dopisany do bazy banych\n", buf->val);
					liczG++;
					clearTab(buf->val, MAX);
					strcpy(buf->val, "Witamy na serwerze!\n");
					if(liczS == 0) strcat(buf->val, "Nie ma jeszcze stolikow, jezeli chcesz go utworzyc wpisz \"nowy\"\n");
					else{
						int i = 0;
						for(i;i<liczS;i++){
							char str[3];
							strcat(buf->val, "Stolik ");
							if((i+1)<10)strcat(buf->val, "0");
							sprintf(str, "%d", (i+1));
							strcat(buf->val, str);
							strcat(buf->val, ":\tzajete ");
							sprintf(str, "%d", stolik[i].zajete);
							strcat(buf->val, str);
							strcat(buf->val, "\n");
						}
					}
				}
				if(msgsnd(msgSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){
					perror("Wyslanie odp na login");
					exit(1);
				}
				usleep(10);
			}
			else{
				printf("Nie ma juz miejsca na serwerze dla %s.\n", buf->val);
				clearTab(buf->val, MAX);
				strcpy(buf->val, "Serwer zapelniony. Przepraszamy.\n");
				buf->nr = -1;
				if(msgsnd(msgSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){
					perror("Wyslanie odp na login");
				}
			}
		}

		//wykonywanie komend
		else if(msgrcv(msgRcv, buf, (sizeof(struct mybuf)-sizeof(long)), CMD, IPC_NOWAIT) != -1){
				printf("Wykonuje polecenie:%s\n", buf->val);
				buf->mtype = INFO;
				//wyslanie info o statusie serwera (stanie pokoi)
				if(checkToN(buf->val, "ping", 4)==1){
					updateDb(gracz, stolik, msgSend);

					clearTab(buf->val, MAX);
					strcat(buf->val, "Dolacz/stworz nowy pokoj");
					int i = 0;
					for(i;i<liczS;i++){
						char str[3];
						strcat(buf->val, "\nStolik ");
						if((i+1)<10)strcat(buf->val, "0");
						sprintf(str, "%d", (i+1));
						strcat(buf->val, str);
						strcat(buf->val, ":\tzajete ");
						sprintf(str, "%d", stolik[i].zajete);
						strcat(buf->val, str);
						strcat(buf->val, "\n");
						buf->st=0;
					}
				}
			//tworzenie nowego pokoju
				else if(checkToN(buf->val, "nowy", 4)==1){
					char* tmp = malloc(sizeof(char) * 30);
					copyFromPoint(tmp, buf->val, 6, 36);
					printf("\nLogin:%s\n",tmp);
					int id = getId(gracz, liczG, tmp);
					if(gracz[id].stolik != 0){
						printf("Operacja niedozwolona\n");
						clearTab(buf->val,MAX);
						strcpy(buf->val,"Nie mozesz utworzyc nowego pokoju bedac juz w jednym!");
					}
					else{
						if(liczS<TBLS){
							if(id==-1){
								printf("Nie znaleziono %s w bazie danych\n",tmp);
								clearTab(buf->val, MAX);
								strcat(buf->val,"Nie ma cie w bazie danych, zaloguj sie ponownie.");
							}
							else{
								stolik[liczS].zajete = 1;
								stolik[liczS].gracze[0] = tmp;
								liczS++;
								printf("nowy Id: %d\n",id+1);
								gracz[id].stolik = liczS;

								clearTab(buf->val, MAX);
								if(liczS<10){
									strcpy(buf->val,"Utworzono pokoj nr 0");
								}
								else{
									strcpy(buf->val, "Utworzono pokoj nr ");
								}

								char str[3];
								sprintf(str, "%d", (liczS));
								strcat(buf->val, str);
								strcat(buf->val, " i dolaczono do niego.");
								buf->st=liczS;
							}
						}
						else{
							clearTab(buf->val,MAX);
							strcpy(buf->val, "Istnieje juz maksymalna liczba pokoi!");
						}
					}
					free(tmp);
				}
			//dolaczanie do istniejacego pokoju
				else if(checkToN(buf->val, "dolacz ", 7)==1){
					char* tmp = malloc(sizeof(char) * 30);
					copyFromPoint(tmp, buf->val, 7, 10); //wyciecie numeru pokoju
					int st = atoi(tmp);
					printf("Pokoj %d\n", st);
					if(liczS<st){
						printf("Nie istnieje pokoj %s\n", tmp);
						clearTab(buf->val, MAX);
						strcpy(buf->val, "Nie istnieje taki pokoj");
					}
					else{
						if(stolik[st-1].zajete==3){
							printf("Pokoj %d jest zajety\n", st);
							clearTab(buf->val, MAX);
							strcpy(buf->val, "Ten pokoj jest juz zapelniony");

						}
						else{
							copyFromPoint(tmp, buf->val, 11, 42);
							printf("Login:%s\n",tmp);
							int id = getId(gracz, liczG, tmp);
							if(id==-1)printf("Nie znaleziono %s w bazie danych\n",tmp);
							else{
								printf("Id: %d\n",id+1);
								gracz[id].stolik = st;
								stolik[st-1].zajete++;
								clearTab(buf->val,MAX);
								if(st<10){
									strcpy(buf->val,"Dolaczono do pokoju nr 0");
								}
								else{
									strcpy(buf->val, "Dolaczono do pokoju nr ");
								}
								int pom=0;
								char str[11];
								sprintf(str, "%d", (st));
								strcat(buf->val, str);
								buf->st=st;

								printf("Status pokoju %d\n", st);
								strcpy(buf->val, "Gracze w twoim pokoju");
								clearTab(str, 11);
								sprintf(str, "(%d):\n", stolik[st-1].zajete);
								strcat(buf->val, str);
								while(pom<stolik[st-1].zajete){
									strcat(buf->val, stolik[st-1].gracze[pom++]);
									strcat(buf->val, "\n");
								}
							}
						}
					}
					free(tmp);
				}
			//wychodzenie z aktualnego pokoju
				else if(checkToN(buf->val, "wyjdz", 5)==1){
					char* tmp = malloc(sizeof(char) * 30);
					copyFromPoint(tmp, buf->val, 7, 37);
					printf("\nLogin:%s\n",tmp);
					int id = getId(gracz, liczG, tmp);
					if(id==-1)
						printf("Nie znaleziono %s w bazie danych\n",tmp);
					else{
						int stol = gracz[id].stolik;
						gracz[id].stolik = 0;
						stolik[stol-1].zajete--;
						updateDb(gracz, stolik, msgSend);

						clearTab(buf->val, MAX);

						printf("Wychodze z pokoju\n");
						int i = 0;
						for(i;i<liczS;i++){
							char str[3];
							strcat(buf->val, "Stolik ");
							if((i+1)<10)strcat(buf->val, "0");
							sprintf(str, "%d", (i+1));
							strcat(buf->val, str);
							strcat(buf->val, ":\tzajete ");
							sprintf(str, "%d", stolik[i].zajete);
							strcat(buf->val, str);
							strcat(buf->val, "\n");
							buf->st=0;
						}
					}
						printf("Id: %d\n",id+1);
					free(tmp);
				}
				else if(checkToN(buf->val, "status", 6)==1){
					char* tmp = malloc(sizeof(char) * 30);
					copyFromPoint(tmp, buf->val, 7, 37);
					printf("\nLogin:%s\n",tmp);
					int id = getId(gracz, liczG, tmp);
					if(id==-1)
						printf("Nie znaleziono %s w bazie danych\n",tmp);
					else{
						int stol = gracz[id].stolik;

						clearTab(buf->val, MAX);
						updateDb(gracz, stolik, msgSend);
						if(stol>0){
							int pom=0;
							printf("Status pokoju %d\n", stol);
							strcpy(buf->val, "Gracze w twoim pokoju");
							char str[11];
							sprintf(str, "(%d):\n", stolik[stol-1].zajete);
							strcat(buf->val, str);
							while(pom<stolik[stol-1].zajete){
								strcat(buf->val, stolik[stol-1].gracze[pom++]);
								strcat(buf->val, "\n");
							}
						}
						else{
							strcpy(buf->val, "Jestes w lobby, przejdz do jednego z pokojow (np. \"dolacz 01\")\n");
							buf->st=0;
						}
					}
					free(tmp);
				}
				else if(checkToN(buf->val, "shutdown", 8)==1){
					char* tmp = malloc(sizeof(char) * 30);
					copyFromPoint(tmp, buf->val, 10, 37);
					printf("\nLogin:%s\n",tmp);
					int id = getId(gracz, liczG, tmp);
					if(id==-1)
						printf("Nie znaleziono %s w bazie danych\n",tmp);
					clearTab(buf->val, MAX);
					if(checkToN(tmp, "serv_admin", 10)==1){
						strcat(buf->val, "Koncze dzialanie serwera");
						printf("WYLACZAM SERWER(rozpoczete gry bd przesylac komunikaty, az sie nie skoncza)\n");
						if(msgsnd(msgSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){
							perror("Wyslanie odp na komende");
						}
						clearTab(buf->val, MAX);
						buf->st=-1;
						strcat(buf->val,"SERWER ZOSTAL WYLACZONY!!!");
						int pl=liczG-1;
						while(pl>0){
							if(msgsnd(msgSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){
								perror("Wyslanie odp na komende");
							}
							pl--;
						}
						//zwalnianie struktur przed zakonczeniem
						free(buf);
						free(stolik);
						free(gracze);
						exit(0);
					}
					else{
						strcat(buf->val, "Nie posiadasz uprawnien administratora!");
					}
				}
				else{
					printf("NIE MA TAKIEJ KOMENDY!\n");
					clearTab(buf->val, MAX);
					strcpy(buf->val, "NIE MA TAKIEJ KOMENDY!");
				}
				if(msgsnd(msgSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){
					perror("Wyslanie odp na komende");
				}
			updateDb(gracz, stolik, msgSend);
		}
	}
	return 0;
}
Beispiel #4
0
void sendDayContent(int msgid, int msgrcv_size, int pid_registration, int pid_patient, struct msgbuf appointment) {
    struct tm appointmentDate = *localtime(&appointment.date_of_visit);
    time_t chosen_date = appointment.date_of_visit;
    //printf("%s", asctime( & appointmentDate ));
    msgrcv_size = 0;
    int i;
    // SENDING REQUEST TO PARENT REGISTRATION
    appointment.typ = getppid();
    appointment.pid = pid_registration;
    msgsnd(msgid, &appointment, MSGBUF_SIZE, 0);
    appointments_list_size = 0;
    while (1) {
        msgrcv(msgid, &appointment, MSGBUF_SIZE, pid_registration, 0);
        if (appointment.index == 1000) {
            break;
        }
        appointments_list[appointments_list_size] = appointment;
        if (appointment.time_of_visit > 0) appointments_list_size++;
    }

    // SENDING INFO ABOUT APPOINTMENTS THAT DAY
    if (appointments_list_size > 0) {
        for (i = 0; i < APPOINTMENTS_LIST_SIZE; i++) {
            struct tm currentDate;
            currentDate = *localtime(&appointments_list[i].date_of_visit);
            if ((currentDate.tm_year == appointmentDate.tm_year) &&
                (currentDate.tm_mon == appointmentDate.tm_mon)
                && (currentDate.tm_mday == appointmentDate.tm_mday)
                    && appointments_list[i].time_of_visit > 0) {
                appointment = appointments_list[i];
                appointment.pid = pid_registration; //APPOINTMENT_ANSWER;
                appointment.typ = pid_patient;
                msgsnd(msgid, &appointment, MSGBUF_SIZE, 0);
            }
        }
    }
    appointment.pid = pid_registration;
    appointment.typ = pid_patient;
    appointment.index = 1000;
    msgsnd(msgid, &appointment, MSGBUF_SIZE, 0);

    // SENDING INFO ABOUT VACATION THAT DAY
    for (i = 0; i < 5; i++) {
        if (vacation_list[i].index == i) {
            time_t start = vacation_list[i].date_of_visit;
            time_t end = vacation_list[i].date_of_visit + (vacation_list[i].time_of_visit * 86400);
            if (chosen_date >= start && chosen_date < end) {
                appointment = vacation_list[i];
                appointment.time_of_visit = 13;
                appointment.pid = pid_registration;
                appointment.typ = pid_patient;
                msgsnd(msgid, &appointment, MSGBUF_SIZE, 0);
            }
        }
    }
    appointment.pid = pid_registration;
    appointment.typ = pid_patient;
    appointment.index = 1000;
    msgsnd(msgid, &appointment, MSGBUF_SIZE, 0);
    return;
}
Beispiel #5
0
void answerForChangeDateOfVisit(int msgid) {
    struct msgbuf new_date;
    int msgrcv_size = msgrcv(msgid, &new_date, MSGBUF_SIZE, CHANGE_VISIT, IPC_NOWAIT);
    if (msgrcv_size > 0) {
        //printf("%s", ctime( & new_date.date_of_visit));
        if (fork() == 0) {
            // choose doctor
            int i;
            int meetings[5];
            for (i = 0; i < 5; i++) { meetings[i] = 0;}
            // if (appointments_list_size > 0)
            for (i = 0; i < APPOINTMENTS_LIST_SIZE; i++) {
                if (appointments_list[i].time_of_visit <= 0) continue;
                int index = atoi(appointments_list[i].password);
                meetings[index] += appointments_list[i].time_of_visit;
            }
            int min_meetings_index = meetings[0];
            for (i = 1; i < 5; i++) {
                if (meetings[i] < meetings[i-1])
                    min_meetings_index = i;
            }
            // CHOOSING TIME
            // set tomorrow's date
            struct tm tomorrow_date;
            const int one_day = 86400;
            time_t tomorrow = today;
            while (true) {                  // cannot be saturday or sunday
                tomorrow = tomorrow + one_day;
                tomorrow_date = *localtime(&tomorrow);
                if (tomorrow_date.tm_wday != 6 && tomorrow_date.tm_wday != 0) break;
            }
            tomorrow_date.tm_hour = 9;
            tomorrow_date.tm_min = 0;
            tomorrow_date.tm_sec = 0;
            tomorrow = mktime(&tomorrow_date);

            int time_difference = (int)difftime(last_date,tomorrow);
            bool founded_date;
            time_t rand_date;
            srand(time(NULL));
            while (!founded_date) {
                founded_date = true;
                int rand_add = rand() % time_difference + 1;
                rand_date = tomorrow + rand_add;
                tomorrow_date = *localtime(&rand_date);
                rand_add = rand() % 13 - new_date.time_of_visit;
                tomorrow_date.tm_hour = 9 + rand_add;
                tomorrow_date.tm_min = 0;
                tomorrow_date.tm_sec = 0;
                rand_date = mktime(&tomorrow_date);
                if (tomorrow_date.tm_wday != 6 && tomorrow_date.tm_wday != 0) {
                    for(i = 0; i < APPOINTMENTS_LIST_SIZE; i++) {
                        int j;
                        bool the_same_pesel = true;
                        for (j = 0; j < 11; j++) {
                            if (appointments_list[i].pesel[j] != new_date.pesel[j]) {
                                the_same_pesel = false;
                                break;
                            }
                        }
                        if (appointments_list[i].index == min_meetings_index || the_same_pesel) {
                            if (rand_date >= appointments_list[i].date_of_visit &&
                                rand_date <= appointments_list[i].date_of_visit +
                                                     (86400*appointments_list[i].time_of_visit)) {
                                founded_date = false;
                                break;
                            }
                            if (vacation_list[min_meetings_index].index == min_meetings_index &&
                                rand_date >= vacation_list[min_meetings_index].date_of_visit &&
                                rand_date <= vacation_list[min_meetings_index].date_of_visit +
                                                     (86400*vacation_list[min_meetings_index].time_of_visit)) {
                                founded_date = false;
                                break;
                            }
                        }
                    }
                }
            }
            // SENDING INFO TO PATIENT
            new_date.date_of_visit = rand_date;
            sprintf(new_date.password,"%d", min_meetings_index);
            strcpy(new_date.name, doctors_list[min_meetings_index].name);
            strcpy(new_date.surname, doctors_list[min_meetings_index].surname);
            new_date.typ = new_date.pid;
            msgsnd(msgid, &new_date, MSGBUF_SIZE, 0);

            exit(getpid());
        }
    }
    return;
}
Beispiel #6
0
int main(int argc, char *argv[])
{
	int ret, use_clone = T_NONE, id, n;
	char *tsttype = NONESTR;
	char buf[7];

	setup();

	if (argc != 2) {
		tst_resm(TFAIL, "Usage: %s <clone|unshare|none>", argv[0]);
		tst_resm(TFAIL, " where clone, unshare, or fork specifies"
			 " unshare method.");
		tst_exit();
	}

	/* Using PIPE's to sync between container and Parent */
	if (pipe(p1) == -1) {
		perror("pipe");
		exit(EXIT_FAILURE);
	}
	if (pipe(p2) == -1) {
		perror("pipe");
		exit(EXIT_FAILURE);
	}

	tsttype = NONESTR;

	if (strcmp(argv[1], "clone") == 0) {
		use_clone = T_CLONE;
		tsttype = CLONESTR;
	} else if (strcmp(argv[1], "unshare") == 0) {
		use_clone = T_UNSHARE;
		tsttype = UNSHARESTR;
	}

	id = msgget(KEY_VAL, IPC_CREAT | IPC_EXCL | 0600);
	if (id == -1) {
		perror("msgget");
		/* Retry without attempting to create the MQ */
		id = msgget(KEY_VAL, 0);
		if (id == -1)
			perror("msgget failure"), exit(1);
	}

	msg.mtype = 5;
	strcpy(msg.mtext, "Message of type 5!");
	n = msgsnd(id, &msg, strlen(msg.mtext), 0);
	if (n == -1)
		perror("msgsnd"), tst_exit();

	tst_resm(TINFO, "mesgq namespaces test : %s", tsttype);
	/* fire off the test */
	ret = do_clone_unshare_test(use_clone, CLONE_NEWIPC, check_mesgq, NULL);
	if (ret < 0) {
		tst_resm(TFAIL, "%s failed", tsttype);
		tst_exit();
	}

	close(p1[0]);
	close(p2[1]);
	write(p1[1], "go", 3);

	read(p2[0], buf, 7);
	if (strcmp(buf, "exists") == 0) {
		if (use_clone == T_NONE)
			tst_resm(TPASS, "Plain cloned process found mesgq "
				 "inside container");
		else
			tst_resm(TFAIL,
				 "%s: Container init process found mesgq",
				 tsttype);
	} else {
		if (use_clone == T_NONE)
			tst_resm(TFAIL,
				 "Plain cloned process didn't find mesgq");
		else
			tst_resm(TPASS, "%s: Container didn't find mesgq",
				 tsttype);
	}

	/* Delete the mesgQ */
	id = msgget(KEY_VAL, 0);
	msgctl(id, IPC_RMID, NULL);

	tst_exit();

	tst_exit();
}
//定时器执行任务的循环线程
static void* thread_timer(void* p)
{
	struct timespec tn;
	S_TIMER_MSG_BUF buf;
	const UCHAR sizeSend = sizeof(buf.id);
	buf.type = MSG_TYPE_FOR_TIMER;
	
	while (1)
	{
		sem_wait(&g_sem);
		if (list_end(&g_listTimerWork) == list_begin(&g_listTimerWork))
		{
			sem_post(&g_sem);
			sem_wait(&g_sem_new);
			continue;
		}
		
		st_timer* timer_t = (st_timer*)list_begin(&g_listTimerWork);
		struct timeval tv={0, 0};
		gettimeofday (&tv , NULL);
		
		if (timer_t->state == 0)
		{
			list_pop_front(&g_listTimerWork);
			list_push_back(&g_listTimerFree, &timer_t->list);
			printf_debug3("KillTimer  id=%d\n", timer_t->id);
			sem_post(&g_sem);
			continue;
		}

		if(cmptime(&tv, &timer_t->tv))
		{
			timer_t->tv.tv_usec = (timer_t->tv.tv_usec + timer_t->interval.tv_usec);
			timer_t->tv.tv_sec = (timer_t->tv.tv_sec + timer_t->interval.tv_sec) + timer_t->tv.tv_usec / 1000000;
			timer_t->tv.tv_usec %= 1000000;
			list_pop_front(&g_listTimerWork);
			if (timer_t->func != NULL)
			{
				pFuncTimer func = (pFuncTimer)timer_t->func;
				insertTimer(timer_t->id);
				sem_post(&g_sem);
				func(timer_t->parameter);
			}else if (timer_t->msgid >= 0)
			{
				buf.id = timer_t->id;
				msgsnd(timer_t->msgid, &buf, sizeSend, 0);
				if (timer_t->times > 0)
				{
					timer_t->times--;
					if (timer_t->times <= 0)
					{
						timer_t->state = 0;
						list_push_back(&g_listTimerFree, &timer_t->list);
						printf_debug3("KillTimer  id=%d\n", timer_t->id);
						sem_post(&g_sem);
						continue;
					}
				}
				insertTimer(timer_t->id);
				sem_post(&g_sem);
			}else
			{
				timer_t->state = 0;
				list_push_back(&g_listTimerFree, &timer_t->list);
				sem_post(&g_sem);
				LOG_WRITE_POS(LOG_ERR, "id=%d, msgid=%d, func=%x\n", timer_t->id, timer_t->msgid, timer_t->func);
			}
		}else
		{
			printf_debug3("Head time: %ld, %ld\r\n", timer_t->tv.tv_sec, timer_t->tv.tv_usec);
			printf_debug3("Cur  time: %ld, %ld\r\n", tv.tv_sec, tv.tv_usec);
			sem_post(&g_sem);
			tn.tv_sec = timer_t->tv.tv_sec;//timer_t->tv.tv_sec - tv.tv_sec;
			tn.tv_nsec = timer_t->tv.tv_usec * 1000;//(timer_t->tv.tv_usec - tv.tv_usec) * 1000;
			sem_timedwait(&g_sem_new, &tn);
		}
	}

	return NULL;
};
Beispiel #8
0
int main(int ac, char **av)
{
	int lc;
	char *msg;
	void check_functionality(void);
	int status, e_code;

	if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) {
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);
	}
#ifdef UCLINUX
	maybe_run_child(&do_child, "d", &msg_q_1);
#endif

	setup();		/* global setup */

	/* The following loop checks looping state if -i option given */

	for (lc = 0; TEST_LOOPING(lc); lc++) {
		/* reset tst_count in case we are looping */
		tst_count = 0;

		/*
		 * fork a child to read from the queue while the parent
		 * enqueues the message to be read.
		 */
		if ((c_pid = FORK_OR_VFORK()) == -1) {
			tst_brkm(TBROK, cleanup, "could not fork");
		}

		if (c_pid == 0) {	/* child */
#ifdef UCLINUX
			if (self_exec(av[0], "d", msg_q_1) < 0) {
				tst_brkm(TBROK, cleanup, "could not self_exec");
			}
#else
			do_child();
#endif
		} else {	/* parent */
			/* put the message on the queue */
			if (msgsnd(msg_q_1, &snd_buf, MSGSIZE, 0) == -1) {
				tst_brkm(TBROK, cleanup,
					 "Couldn't enqueue" " message");
			}
			/* wait for the child to finish */
			wait(&status);
			/* make sure the child returned a good exit status */
			e_code = status >> 8;
			if (e_code != 0) {
				tst_resm(TFAIL, "Failures reported above");
			}

		}
	}

	cleanup();
	tst_exit();

    /** NOT REACHED **/

}
Beispiel #9
0
void handle_server_heartbeat(void* received, int msg_type){
    MSG_SERVER2SERVER ping = *(MSG_SERVER2SERVER*)(received);
    int receiver = ping.server_ipc_num;
    ping.server_ipc_num = MSG_RECEIVER;
    msgsnd(receiver, &ping, _size(MSG_SERVER2SERVER), 0);
}
Beispiel #10
0
int main(int argc, char *argv[]){
    int b, k;
    int arg = atoi(argv[1]);
    if (arg == -1){
        closeserver();
    }
    if (arg == 0){
        printf("Please give the number of clients\n");
        exit(0);
    }
    arg = arg-2;
    b = fork();
    if (b != 0){
        for (k = 0; k < arg; k++){
            if (b == 0){
                continue;
            }else{
                b = fork();
            }
        }
    }
    Table *table = malloc(sizeof(Table));
    int i, j;
    int key = 9999;
    int key2 = 8888;
    table->mtype = getpid();
    table->complete = 0;
    table->matrix[0][0] = 'a';
    table->matrix[0][1] = 'b';
    table->matrix[0][2] = 'c';
    table->matrix[1][0] = 'd';
    table->matrix[1][1] = 'e';
    table->matrix[1][2] = 'f';
    table->matrix[2][0] = 'g';
    table->matrix[2][1] = 'h';
    table->matrix[2][2] = 'i';
    srand(time(NULL));
    int id = msgget(key, 0666);
    int id2 = msgget(key2, 0666);
    if (id < 0 || id2 < 0){
        perror("Something went wrong!");
    }
    while (!table->complete){
        msgsnd(id, table, sizeof(Table), 0);
        msgrcv(id2, table, sizeof(Table), getpid(), 0);
        if (b == 0){sleep(0.001);}
        //printf("\n-------|%d|-------\n", getpid());
        //displaygame(table->matrix);
        //printf("\n---------------\n");
        table->complete = gamestatus(table->matrix);
        if (table->complete == 1){
            //displaygame(table->matrix);
            printf("In game: %d, server won!\n", getpid());
            break;
        }
        if (table->complete == 2){
            //displaygame(table->matrix);
            printf("In game: %d. client  %d won!\n", getpid(), getpid());
            break;
        }
        if (table->complete == 3){
            //displaygame(table->matrix);
            printf("In game: %d, it's draw!\n", getpid());
            break;
        }
        int Oed = 0;
        while (!Oed){
            i = rand() % 3;
            j = rand() % 3;
            if ((table->matrix[i][j] != 'X') && (table->matrix[i][j] != 'O')){
                table->matrix[i][j] = 'O';
                Oed = 1;
            }
        }
    }
    if (b != 0){
        for (k = 0; k < arg; k++){
            wait(0);
        }
    }else{
        exit(0);
    }
    return 0;
}
Beispiel #11
0
int main()
{
    printf("sizeof(msg_struct) : %ld", sizeof(MSG_STRUCT));
    // utworzenie klucza
    key_t key = ftok("./../..", 'L');

    if (key == -1)
    {
        perror("\nSERWER: Blad utworzenia klucza");
        printf("\tERRNO = %d", errno);
        exit(EXIT_FAILURE);
    }

    printf("\nSERWER: Utworzylem klucz: %d", key);

    // utworzenie kolejki komunikatów
    queue_id = msgget(key, IPC_CREAT|IPC_EXCL|0600);

    if (queue_id == -1)
    {
        perror("\nSERWER: Blad utworzenia kolejki komunikatow");
        printf("\tERRNO = %d", errno);
        exit(EXIT_FAILURE);
    }

    printf("\nSERWER: Utworzylem kolejke komunikatow o id: %d", queue_id);

    signal(SIGINT, the_end);

    MSG_STRUCT msg;
    int msg_recieve;
    int msg_send;

    while(1)
    {
        printf("\nSERWER: Czekam na wiadomosc\n");

        // odbieranie komunikatu
        msg_recieve = msgrcv(queue_id, &msg, sizeof(MSG_STRUCT) - sizeof(long int) + 1, 1, 0);

        if (msg_recieve == -1)
        {
            perror("\nSERWER: Blad odbioru wiadomosc");
            printf("\tERRNO = %d", errno);
            msg_rem(queue_id);
            exit(EXIT_FAILURE);
        }

        printf("\nSERWER: Odebralem wiadomosc od %ld\n\tTresc: %s", msg.sender, msg.message);

        msg.reciever = msg.sender;

        // powiększanie otrzymanego tekstu
        char* i = msg.message;
        for (i; *i != '\0'; i++)
            *i = toupper(*i);

        // wysyłanie komunikatu zwrotnego
        msg_send = msgsnd(queue_id, &msg, sizeof(MSG_STRUCT) - sizeof(long int) + 1, IPC_NOWAIT);

        if (msg_send == -1)
        {
            perror("\nSERWER: Blad wyslania wiadomosci");
            printf("\tERRNO = %d", errno);
            msg_rem(queue_id);
            exit(EXIT_FAILURE);
        }

        printf("\nSERWER: Wyslalem wiadomosc zwrotna do %ld", msg.sender);
    }

    exit(0);
}
Beispiel #12
0
int main(int argc, char* argv[]){

  if(argc != 1){
    printf("Benutzung ./server\n");
    return EXIT_FAILURE;
  }

//Setup für SignalHandler bei Ctrl+C (SIGINT)

struct sigaction action = {};
action.sa_handler = &SIGINThandler;
sigaction(SIGINT, &action, NULL);

key_t key;


struct msg{
  long mtype;
  char mtext[BUFLEN];
}msg1;

int fileSize;
int erg = -1; // Erg ist für writevorgang und do-while schleife
int anzahl; //Anzahl an zu empfangenden Packeten
int rest; //Größe des letzten zu senden Packets

//vorbereitung für rcv von namen (mtype = 10) und Erstellung der MsgQ
while(1){
msg1.mtype = 10;

key = ftok("server.c", 10); // 10 ist Projektid
if (key < 0) {
  perror("Fehler bei KeyErzeugung");
    return EXIT_FAILURE;
}

id = msgget(key, IPC_CREAT | 0666);
if (id < 0) {
  perror("Fehler bei MsgQ Erstellung");
  if(atexit(closeQ) != 0){
    perror("Fehler beim atexit(closeQ) call");
  }
  return EXIT_FAILURE;
}

if(msgrcv(id, &msg1, sizeof(msg1.mtext), msg1.mtype, 0) < 0){
  perror("Fehler beim recieven");
  if(atexit(closeQ) != 0){
    perror("Fehler beim atexit(closeQ) call");
  }
  return EXIT_FAILURE;
}

printf("Name der Zieldatei: %s \n", msg1.mtext); //DEbug Ausgabe der Nachricht

char *pathZiel = msg1.mtext;

int fd = open(pathZiel, O_CREAT | O_WRONLY | O_EXCL, S_IRUSR | S_IWUSR);
msg1.mtype = 20;
if(fd < 0){
  if(errno == EEXIST){
    //Datei existiert bereits
    //Sende Ablehnung an Client

    strcpy(msg1.mtext, "NAK"); //Ablehnung bei Datei vorhanden
    if(msgsnd(id, &msg1, sizeof(msg1.mtext), 0) < 0){
      perror("Fehler beim Senden der Ablehnung");
      if(atexit(closeQ) != 0){
        perror("Fehler beim atexit(closeQ) call");
      }
      return EXIT_FAILURE;
    }
  }
} else {      //Datei vorhanden, weiterer Ablauf unter else
    strcpy(msg1.mtext, "ACK");      //Bestätigung bei Datei nicht vorhanden;
    if(msgsnd(id, &msg1, sizeof(msg1.mtext), 0) < 0){
      perror("Fehler beim senden der Bestätigung");
      if(atexit(closeQ) != 0){
        perror("Fehler beim atexit(closeQ) call");
      }
      return EXIT_FAILURE;
    }
    //Vorbereitung fürs Empfangen der Dateilänge
    msg1.mtype = 30;

    if(msgrcv(id, &msg1, sizeof(msg1.mtext), msg1.mtype, 0) < 0){
      perror("Fehler beim empfangen der Dateigröße");
      if(atexit(closeQ) != 0){
        perror("Fehler beim atexit(closeQ) call");
      }
      return EXIT_FAILURE;
    }

    fileSize = atoi(msg1.mtext);
    printf("Dateigröße: %d Bytes\n", fileSize);

    //Vorbereitung zum empfangen der Daten
    msg1.mtype = 40;

    anzahl = fileSize / sizeof(msg1.mtext);
    rest  = fileSize % sizeof(msg1.mtext);

    printf("Anzahl 100%% gefüllter Blöcke: %d, Groesse des Rest/Letzten Blocks: %d Byte\n",anzahl, rest);
    int i;
    for (i = 1; i <= anzahl ; i++) {    //x-malige durchläufe von vollen Packeten, abhängig von anzahl
        if(msgrcv(id, &msg1, sizeof(msg1.mtext), msg1.mtype, 0) < 0){
          perror("Fehler beim empfangen der Daten");
          if(atexit(closeQ) != 0){
            perror("Fehler beim atexit(closeQ) call");
          }
          return EXIT_FAILURE;
        }
        printf("Block %d empfangen\n", i);
        erg = write(fd, msg1.mtext, sizeof(msg1.mtext));
        if (erg < 0)  {
          perror("Fehler beim Schreiben der Daten");
          if(atexit(closeQ) != 0){
            perror("Fehler beim atexit(closeQ) call");
          }
          return EXIT_FAILURE;
        }
    }

    //Abschließendes Senden des Rest-Packetes
    if(msgrcv(id, &msg1, sizeof(msg1.mtext), msg1.mtype, 0) < 0){
      perror("Fehler beim empfangen der Daten");
      if(atexit(closeQ) != 0){
        perror("Fehler beim atexit(closeQ) call");
      }
      return EXIT_FAILURE;
    }
    printf("Rest Block empfangen\n");
    printf("---------------------------------------------\n");
    erg = write(fd, msg1.mtext, rest);
    if (erg < 0)  {
      perror("Fehler beim Schreiben der Daten");
      if(atexit(closeQ) != 0){
        perror("Fehler beim atexit(closeQ) call");
      }
      return EXIT_FAILURE;
    }
  } // Ende vom Datei vorhanden Ablauf

  //closeQ();
}
  atexit(closeQ);
//LÖschen der Q, nach beendigung von allen Vorgängen
return EXIT_SUCCESS;
}
Beispiel #13
0
int main()
{
    int request;
    reqReservation_t reservation;
    reqConsultation_t consultation;
    ansReservation_t ansRes;
    ansConsultation_t ansCons;

    int msqid;

    pid_t monPid = getpid();
    startingMessage();

    while(1)
    {
        printf("Veuillez sélectionner le type de requête que vous souhaitez effectuer :\n");
        printf("     1 pour une consultation, 2 pour une réservation ou un autre chiffre pour quitter\n");
        scanf("%d", &request);

        switch(request)
        {
        case CONS:
            consultation.client = monPid;
            consultation.date = saisiDate(CONS);
            consultation.mtype = mtype_demandeConsultation;

            if ((msqid = msgget(CONSULTATION_KEY, 0)) < 0)
            {
                perror("ERROR msgget consultation");
                exit(EXIT_FAILURE);
            }
            if (msgsnd(msqid, &consultation, sizeof(reqConsultation_t) - sizeof(long), 0) < 0)
            {
                perror("ERROR msgsnd consultation");
                exit(EXIT_FAILURE);
            }
            if (msgrcv(msqid, &ansCons, sizeof(ansConsultation_t) - sizeof(long), monPid, 0) == -1)
            {
                perror("ERROR msgrcv consultation");
                exit(EXIT_FAILURE);
            }

            printf("Il reste/restait %d places pour le %04d-%02d-%02d\n", ansCons.nbplace, consultation.date.annee, consultation.date.mois, consultation.date.jour);

            break;
        case RES:
            reservation.client = monPid;
            reservation.date = saisiDate(RES);
            reservation.nbPlace = saisiNbPlace();
            reservation.mtype = mtype_demandeReservation;

            if ((msqid = msgget(RESERVATION_KEY, 0)) < 0)
            {
                perror("ERROR msgget réservation");
                exit(EXIT_FAILURE);
            }

            if (msgsnd(msqid, &reservation, sizeof(reqReservation_t) - sizeof(long), 0) < 0)
            {
                perror("ERROR msgsnd réservation");
                exit(EXIT_FAILURE);
            }
            if (msgrcv(msqid, &ansRes, sizeof(ansReservation_t) - sizeof(long), monPid, 0) < 0)
            {
                perror("ERROR msgrcv réservation");
                exit(EXIT_FAILURE);
            }

            printf("%s\n", ansRes.message);

            break;
        default:
            printf("Vous avez choisi de quitter\n");
            printf("Exit\n");
            exit(EXIT_SUCCESS);
            break;
        }
    }
    return(EXIT_SUCCESS);
}
Beispiel #14
0
int main(int argc, char *argv[])
{
	FILE *file;
	struct msgbuf *msg1, *msg2;
	unsigned char *ptr1, *ptr2;
	int id1, id2;
	int i, j, k;

	msg1 = malloc(sizeof(*msg1) + 1024);
	msg2 = malloc(sizeof(*msg2) + 1024);
	if (!msg1 || !msg2) {
		perror("malloc");
		exit(1);
	}

	ptr1 = (unsigned char *) msg1->mtext;
	ptr2 = (unsigned char *) msg2->mtext;

	for (i = 0, k = 0; i < 1024; i++, k = (k + 1) % 256) {
		ptr1[i] = k;
		ptr2[i] = 255 - k;
	}
		
	close(0);
	close(1);
	close(2);

	unlink(OUTFILE);
	file = fopen(OUTFILE, "w+");
	if (!file) {
		perror("open");
		exit(1);
	}
	if (dup2(0,2) < 0) {
		perror("dup2");
		exit(1);
	}
	
	id1 = msgget(MSG_KEY, 0700|IPC_CREAT|IPC_EXCL);
	if (id1 < 0) {
		perror("msgget1");
		exit(1);
	}
	id2 = msgget(IPC_PRIVATE, 0700|IPC_CREAT|IPC_EXCL);
	if (id2 < 0) {		
		perror("msgget2");
		exit(1);
	}

	for (j = 0; j < MSG_NUM; j++) {
		msg1->mtype = j+1;
		msg2->mtype = (j+1) * 10;
		if (msgsnd(id1, msg1, 1024, 0) < 0) {
			perror("msgsnd1");
			exit(1);
		}
		if (msgsnd(id2, msg2, 1024, 0) < 0) {
			perror("msgsnd2");
			exit(1);
		}
	}

	fprintf(file, "sent messages, sleeping 20\n");
	fflush(file);
	sleep(15);
	fprintf(file, "waking up\n");
	fflush(file);

	for (j = 0; j < MSG_NUM; j++) {
		memset(ptr1, 0, 1024);
		memset(ptr2, 0, 1024);
		if (msgrcv(id1, msg1, 1024, j+1, 0) < 0) {
			perror("msgrcv1");
			exit(1);
		}
		if (msgrcv(id2, msg2, 1024, (j+1)*10, 0) < 0) {
			perror("msgrcv2");
			exit(1);
		}
		for (i = 0, k = 0; i < 1024; i++, k = (k + 1) % 256) {
			if (ptr1[i] != k || ptr2[i] != 255 - k) {
				fprintf(file, "mismatch at %d\n", i);
				fflush(file);
				break;
			}
		}
	}

	if (msgctl(id1, IPC_RMID, NULL) < 0)
		perror("rmid1 again");
	if (msgctl(id2, IPC_RMID, NULL) < 0)
		perror("rmid2 again");

	fprintf(file, "completed\n");
	fflush(file);

	fclose(file);
	return 0;
}
void BorneReservation::Selectionner()
{
	Trace("BorneReservation::Selectionner()");
	
	char choixBuff[80];
	char placesBuff[80];
	int choix, nPlaces;
	
	strcpy(choixBuff, lineChoix->text());
	choix = atoi(choixBuff);
	
	strcpy(placesBuff, lineNbPlaces->text());
	nPlaces = atoi(placesBuff);
	
	if (choix) {
		MESSAGE msg;
		msg.sender = getpid();
		
		if (nPlaces <= 0) { // Consultation des événements disponibles d'un type
			MENU menu = { choix, 0 };
			
			// Annule une consultation en cours
			if (ProcessReservation != 0)
				this->Annuler();

			// Demande la liste d'un type d'événement
			msg.dest = SERVER_RECV;
			msg.type = CONSULTER_EVENTS;
			msg.data.menu = menu;
			
			if (msgsnd(IdQueue, &msg, MESSAGE_SIZE, 0) != 0) {
				TraceErreur("Erreur de msgsnd()...");
				exit(1);
			}
			Trace("Message de listage des événements emis\n");
			
			// Reçoit la liste des événements
			if (msgrcv(IdQueue, &msg, MESSAGE_SIZE, getpid(), 0) == -1) {
				TraceErreur("Erreur de msgrcv()...");
				exit(1);
			}
			
			// Affiche la liste des événements
			textMenu->clear();
			
			ProcessReservation = msg.sender;
			
			char buff[1000];
			buff[0] = '\0';
		
			Trace("Evénements reçus de %d", ProcessReservation);
				
			for (int i = 0; i < MAX_EVENTS; i++) {
				if (msg.data.events[i].nom[0] != '\0') {
					char tempBuff[1000];
					
					sprintf(tempBuff, "%2d - %-20s%s %-20s %3d\n",
						i + 1, msg.data.events[i].nom, msg.data.events[i].date,
						msg.data.events[i].localisation, msg.data.events[i].libre);
				
					strcat(buff, tempBuff);
				}
			}
			AffichageMenu(buff);
		} else { // Réservation des places
			Trace("Emission à %d", (int) ProcessReservation);
			
			msg.dest = ProcessReservation;
			msg.type = RESERVATION;
			
			msg.data.menu.choix = choix;
			msg.data.menu.nPlaces = nPlaces;
			
			if (msgsnd(IdQueue, &msg, MESSAGE_SIZE, 0) != 0) {
				TraceErreur("Erreur de msgsnd()...");
				exit(1);
			}
			
			AffichageMenu("En attente de la réponse du serveur ...\n" // FIXME
				      "Cela peut prendre une vingtaine de secondes");
			
			// Valide la réservation
			if (msgrcv(IdQueue, &msg, MESSAGE_SIZE, getpid(), 0) == -1) {
				TraceErreur("Erreur de msgrcv()...");
				exit(1);
			}
			
			
			if (msg.type == OK)
				AffichageMenu("Comfirmez la réservation, vous avez 20 secondes");
			else if (msg.type == STOCK_INSUFFISANT) {
				TraceErreur("Il n'y a plus assez de place pour l'événement");
				
				AfficherMenuPrincipal(0);
			}
		}
	}
}
Beispiel #16
0
void handle_message(void* received, int msg_type){
    MSG_CHAT_MESSAGE msg = *(MSG_CHAT_MESSAGE*)(received);
    
    MSG_RESPONSE rsp;
    rsp.type = RESPONSE;
    
    if (msg.msg_type == PUBLIC) {
        
        if (is_local_user(msg.sender)) {
            // if sender send msg to its parent server

            int servers_to_removed[REPO_SIZE];
            int servers_to_send[REPO_SIZE];
            
            int i;
            
            for (i=0; i<REPO_SIZE; ++i) {
                servers_to_send[i] = 0;
                servers_to_removed[i] = 0;
            }
        
            lock_repo();
                int j,k;
                int all_servers_exists = TRUE;
                for (i=0, j=0, k=0; i<REPO_SIZE; ++i) {
                    if ( !strcmp(SHM_ROOM_SERVER_ADRESS[i].room_name, msg.receiver) &&
                    SHM_ROOM_SERVER_ADRESS[i].server_id != MSG_RECEIVER &&
                    SHM_ROOM_SERVER_ADRESS[i].server_id != -1   ) {
                        if (!await_server_response(SHM_ROOM_SERVER_ADRESS[i].server_id)) {
                            all_servers_exists = FALSE;
                            servers_to_removed[j] = SHM_ROOM_SERVER_ADRESS[i].server_id;
                            ++j;
                        } else {
                            servers_to_send[k] = SHM_ROOM_SERVER_ADRESS[i].server_id;
                            ++k;
                        }
                    }
                }
            unlock_repo();
            
            if (all_servers_exists) {
                for (i=0; i<REPO_SIZE; ++i) {
                    if (servers_to_send[i]) {
                        msgsnd(servers_to_send[i], &msg, _size(MSG_CHAT_MESSAGE), 0);
                    }
                }
            } else {
                for (i=0; i<REPO_SIZE; ++i) {
                    if(servers_to_removed[i]) {
                        remove_server(servers_to_removed[i]);
                    }
                }
                rsp.response_type = MSG_NOT_SEND;
                strcpy(rsp.content, "NOT EVERY SERVER RESPONDED");
            }
            
            
            for (i=0; i<MAX_USERS_NUMBER; ++i) {
                if( !strcmp(LOCAL_REPO[i].room_name, msg.receiver) ) {
                    msgsnd(LOCAL_REPO[i].client_id, &msg, _size(MSG_CHAT_MESSAGE), 0);
                }
            }
        } else {
            // if we are the second server and we send msg to users
            
            int i;
            for (i=0; i<MAX_USERS_NUMBER; ++i) {
                if( !strcmp(LOCAL_REPO[i].room_name, msg.receiver) ) {
                    msgsnd(LOCAL_REPO[i].client_id, &msg, _size(MSG_CHAT_MESSAGE), 0);
                }
            }
            
            
        }
        
    } else if (msg.msg_type == PRIVATE) {
        
        int node_server_id = check_if_user_exists(msg.receiver);
        
        if(node_server_id == MSG_RECEIVER) {
            msgsnd(get_user_id(msg.receiver), &msg, _size(MSG_CHAT_MESSAGE), 0);
        } else if (node_server_id != FALSE) {
            if (await_server_response(node_server_id)) {
            
                msgsnd(node_server_id, &msg, _size(MSG_CHAT_MESSAGE), 0);
            } else {
                rsp.response_type = MSG_NOT_SEND;
                strcpy(rsp.content, "SERVER DID NOT RESPOND");
                remove_server(node_server_id);
            }
        } else if (node_server_id == FALSE) {
            rsp.response_type = MSG_NOT_SEND;
            strcpy(rsp.content, "USER DOESNT EXIST!");
        }
    }
    msgsnd(get_user_id(msg.sender), &rsp, _size(MSG_RESPONSE), 0);
}
Beispiel #17
0
//     if(args[siz-1][strlen(args[siz-1])-1] == '&')
//     {
//         args[siz-1][strlen(args[siz-1])-1] = '\0';
//         BG = 1;
//     }
//     if((pidc = fork()) < 0)
//         perror("");
//     else if(pidc == 0)
//     {   
//         // printf("%s\n",args[0] );
//         if(execvp(args[0], args) < 0)
//             printf("Cannot execute");
//         else
//             printf("Successfully Executed\n");
//         exit(1);
//     }
//     else
//     {
//         if(BG==0)
//             pid1 = waitpid(pidc, &status, 0);
//     }
// }
int main(void)
{
	struct my_msgbuf buf;
	int msqid;
	key_t key;
	pid_t pid;
	int dir[2];
	pipe2(dir,O_NONBLOCK);
	pid=fork();
	
	if ((key = ftok("server.c", 'H')) == -1) {
			perror("ftok");
			exit(1);
		}

		if ((msqid = msgget(key, 0644 )) == -1) {
			perror("msgget");
			exit(1);
		}
		
	if(!pid)
	{
		for(;;) { /* Spock never quits! */
			if (msgrcv(msqid, &buf, sizeof (struct my_msgbuf), getppid(), 0) == -1) {
				perror("msgrcv");
				exit(1);
			}
			
			char  hist_loc[100];
			printf("%s\n",buf.mtext );
			getcwd(hist_loc, 100);
			char directory[200];
			memset(directory,0,200);
			int reads=read(dir[0],directory,200);
			if(reads>0)
				fprintf(stderr,"%s $ ",directory );
			else
				fprintf(stderr,"%s $ ",hist_loc );

			
   		 	
			if(strcmp(buf.mtext,"couple")==0)
			{
				//pidarray[clients++]=buf.pid;;
			}


		}
	}	
	else
	{
		close(dir[0]);
		char  hist_loc[100];
   		getcwd(hist_loc, 100);	
   		printf("%s $ ",hist_loc );
		buf.mtype = 10; /* we don't really care in this case */
		buf.pid=getpid();
		while(fgets(buf.mtext, sizeof buf.mtext, stdin) != NULL) 
		{
			int len = strlen(buf.mtext);
			char  hist_loc[100];
			
			

			/* ditch newline at end, if it exists */
			if (buf.mtext[len-1] == '\n') buf.mtext[len-1] = '\0';
			 
			if(strcmp(buf.mtext,"decouple")==0)
				return;
			else if(strcmp(buf.mtext,"couple")==0);

			else
			{
				int pipes[2];
				pipe2(pipes,O_NONBLOCK);
				// pipe2(err,O_NONBLOCK);
				// printf("lol\n");
				// printf("%d\n",STDERR_FILENO );
	            int saved_state_out=redirect(1,pipes[1]);
	            // int error_state=redirect(STDERR_FILENO,err[1]);

				char* tokens[100];
	            tokens[0] = (char*)malloc(1000*sizeof(char));
	            char temp[1000];
	            strcpy(temp,buf.mtext);
	            tokens[0] = strtok(temp, " ");
	            int i=1;
	           
	            while(tokens[i-1] != NULL)
	            {   
	                tokens[i] = (char *)malloc(100*sizeof(char));
	                tokens[i] = strtok(NULL, " ");
	                i++;
	            }
	            if(!strcmp(tokens[0],"history"))
	            {
	            	//history ka code copy paste
	            	fprintf(stderr, "not here");

	            }
	            else if(!strcmp(tokens[0],"cd"))
	            {

	            	if(tokens[1]!=NULL)
	                {
	                    int status=chdir(tokens[1]);
	                    if(status==-1)
	                        perror("cd ");
	                }
	                else
	                    chdir(getenv("HOME"));
	                char tempdir[200];
	                getcwd(tempdir, 200);
	                
          			write(dir[1], tempdir, 200);  /* Write data on pipe */

		        }    
				else
				{

						system(buf.mtext);
				}
				memset(tokens[0],'\0',100);
				close(pipes[1]);
				// close(err[1]);
				// fprintf(stderr, "%s\n", buf.mtext);

				int readit=read(pipes[0],tokens[0],2000);
				int flag=0;
				// fprintf(stderr, "%s\n",tokens[0] );
				if(readit>0)
				{
					if(strcmp(tokens[0],"\0"))
					{
						strcat(buf.mtext,"\n");
						strcat(buf.mtext,tokens[0]);
						flag=1;
						// int errd=read(err[0],tokens[0],2000);

						// if(errd>0)
						// {
						// 	if(strcmp(tokens[0],"\0"))
						// 	{
						// 		strcat(buf.mtext,tokens[0]);
						// 	}
						// }
					}
				}
				close(pipes[0]);
				// close(err[0]);
				restore(saved_state_out,1);
				// printf("%s\n",tokens[0] );
				// restore(error_state,STDERR_FILENO);
				if(flag)
					fprintf(stdout, "%s\n", tokens[0]);

				
			}
			if (msgsnd(msqid, &buf, sizeof(struct my_msgbuf), 0) == -1) /* +1 for '\0' */
				perror("msgsnd");
			
			getcwd(hist_loc, 100);	
   			fprintf(stderr,"%s $ ",hist_loc );
	
		}
		// close(dir[1]);

		if (msgctl(msqid, IPC_RMID, NULL) == -1) {
			perror("msgctl");
			exit(1);

		}
		
	}

	return 0;
}
Beispiel #18
0
int main(int args, char* argv[]){

    signal(SIGINT,interrupt);

    printf("OCZEKIWANIE NA DRUGIEGO GRACZA\n");

    /* SPRAWDZANIE POPRAWNOSCI ARGUMENTOW */

    if(args<4){
        printf("NIEWLASCIWA LICZBA ARGUMENTOW\n");
        exit(1);
    }

    int init_queue_key=atoi(argv[1]);
    int id_gracza=atoi(argv[2]);

    int init_queue_id=msgget(init_queue_key,IPC_CREAT|0664);
    if(init_queue_id==-1){
        perror("BLAD STWORZENIA KOLEJKI INIT");
        exit(1);
    }



    Init_message init_message;
    init_message.mtype=ROZPOCZNIJ;
    init_message.init_data.id_gracza=id_gracza;
    msgsnd(init_queue_id,&init_message,sizeof(init_message.init_data),0);

    msgrcv(init_queue_id,&init_message, sizeof(init_message.init_data),AKCEPTUJ,0);

    int game_queue_key=init_message.init_data.id_kolejki_kom;

    game_queue_id=msgget(game_queue_key,IPC_CREAT|0664);
    if(game_queue_id==-1){
        perror("Blad przy otwarciu kolejki do komunikacji");
        exit(1);
    }


    int output_queue_key=atoi(argv[3]);
    output_queue_id=msgget(output_queue_key,IPC_CREAT|0664);
    if(output_queue_id==-1){
        perror("Blad przy tworzeniu kolejki output");
        exit(1);
    }

    init_message.mtype=ID;
    init_message.init_data.id_gracza=id_gracza;
    msgsnd(output_queue_id,&init_message, sizeof(init_message.init_data),0);

    if(fork()==0){

        Game_message train_message;
        train_message.mtype=TWORZ;

        Game_message battle_message;
        battle_message.mtype=ATAK;

        Game_message surrender_message;
        surrender_message.mtype=PODDAJSIE;

        Game_data_struct train_list;
        Game_data_struct battle_list;

        char decyzja;

        char buffer[MAX]="";


        while(1){
            printf("\033[2J\033[1;1H");
            printf("ID GRACZA TO: %d\n",id_gracza);
            printf("WYBIERZ AKCJE:\n1-trening jednostek\n2-atak\n3-poddaj sie\n\n");

            /* Pobranie komendy */
            decyzja=fgetc (stdin);
            /* Usuniecie pozostalosci w stdin */
            flush_input(stdin);

            if(decyzja=='1') {

                printf("Wybierz liczbe jednostek lekkiej piechoty\n");
                fgets (buffer, MAX, stdin);
                train_list.light_infantry=(int)strtol(buffer,NULL,0);

                printf("Wybierz liczbe jednostek ciezkiej piechoty\n");
                fgets (buffer, MAX, stdin);
                train_list.heavy_infantry=(int)strtol(buffer,NULL,0);

                printf("Wybierz liczbe jednostek jazdy\n");
                fgets (buffer, MAX, stdin);
                train_list.cavalry=(int)strtol(buffer,NULL,0);

                printf("Wybierz liczbe robotnikow\n");
                fgets (buffer, MAX, stdin);
                train_list.workers=(int)strtol(buffer,NULL,0);

                train_message.game_data=train_list;
                msgsnd(game_queue_id,&train_message, sizeof(train_message.game_data),0);
                printf("WYSLANO POLECENIE TRENINGU\n");
            }

            else if(decyzja=='2') {
                printf("Wybierz liczbe jednostek lekkiej piechoty\n");
                fgets (buffer, MAX, stdin);
                battle_list.light_infantry=(int)strtol(buffer,NULL,0);

                printf("Wybierz liczbe jednostek ciezkiej piechoty\n");
                fgets (buffer, MAX, stdin);
                battle_list.heavy_infantry=(int)strtol(buffer,NULL,0);

                printf("Wybierz liczbe jednostek jazdy\n");
                fgets (buffer, MAX, stdin);
                battle_list.cavalry=(int)strtol(buffer,NULL,0);

                battle_message.game_data=battle_list;

                msgsnd(game_queue_id,&battle_message, sizeof(battle_message.game_data),0);
                printf("WYSLANO POLECENIE ATAKU\n");
            }
            else if(decyzja=='3'){
                printf("Poddales sie\n");
                msgsnd(game_queue_id,&surrender_message, sizeof(surrender_message.game_data),0);
                msgsnd(output_queue_id,&surrender_message,sizeof(surrender_message.game_data),0);

                kill(0,SIGKILL);

            }
            else {
                printf("NIE MA TAKIEJ KOMENDY\n");
            }

        }

    }
    else {

        Game_message message;
        Game_message response_message;
        response_message.mtype=ODPOWIEDZ;

        msgsnd(output_queue_id, &message, sizeof(message.game_data), 0);



        while (1) {
            msgrcv(game_queue_id, &message, sizeof(message.game_data), 0, 0);
            if (message.mtype == KONIEC || message.mtype == ZAKONCZ) {
                msgsnd(output_queue_id, &message, sizeof(message.game_data), 0);

                sleep(1);

                msgctl(game_queue_id,IPC_RMID,0);
                msgctl(output_queue_id,IPC_RMID,0);

                kill(0, SIGKILL);
            }
            else if (message.mtype == ATAK || message.mtype == TWORZ || message.mtype == PODDAJSIE) {
                msgsnd(game_queue_id, &message, sizeof(message.game_data), 0);
            }
                else if(message.mtype==ZAPYTANIE){
                msgsnd(game_queue_id,&response_message, sizeof(response_message.game_data),0);
            }
            else {
                msgsnd(output_queue_id, &message, sizeof(message.game_data), 0);
            }

        }

    }
}
Beispiel #19
0
int main(int ac, char **av)
{
	int lc;			/* loop counter */
	char *msg;		/* message returned from parse_opts */

	/* parse standard options */
	if ((msg = parse_opts(ac, av, NULL, NULL)) != NULL) {
		tst_brkm(TBROK, NULL, "OPTION PARSING ERROR - %s", msg);
	}

	setup();		/* global setup */

	/* The following loop checks looping state if -i option given */

	for (lc = 0; TEST_LOOPING(lc); lc++) {
		/* reset Tst_count in case we are looping */
		Tst_count = 0;

		/*
		 * Use TEST macro to make the call
		 */

		TEST(msgsnd(msg_q_1, &msg_buf, MSGSIZE, 0));

		if (TEST_RETURN == -1) {
			tst_resm(TFAIL, "%s call failed - errno = %d : %s",
				 TCID, TEST_ERRNO, strerror(TEST_ERRNO));
			continue;
		}

		if (STD_FUNCTIONAL_TEST) {

			/* get the queue status */
			if (msgctl(msg_q_1, IPC_STAT, &qs_buf) == -1) {
				tst_brkm(TBROK, cleanup, "Could not "
					 "get queue status");
			}

			if (qs_buf.msg_cbytes != MSGSIZE) {
				tst_resm(TFAIL, "queue bytes != MSGSIZE");
			}

			if (qs_buf.msg_qnum != 1) {
				tst_resm(TFAIL, "queue message != 1");
			}

			tst_resm(TPASS, "queue bytes = MSGSIZE and "
				 "queue messages = 1");
		} else {
			tst_resm(TPASS, "call succeeded");
		}

		/*
		 * remove the message by reading from the queue
		 */
		if (msgrcv(msg_q_1, &rd_buf, MSGSIZE, 1, 0) == -1) {
			tst_brkm(TBROK, cleanup, "Could not read from queue");
		}
	}

	cleanup();

	tst_exit();
}
Beispiel #20
0
int main(int argc, char *argv[])
{
    int n = argc - 1;//size of the array
    int *array1 = (int*) malloc(sizeof(int)*n);//part 1
    int *array2=(int*) malloc(sizeof(int)*n);//part 2
    int *array=(int*) malloc(sizeof(int)*n);
    for (int i = 0; i < n; i++)
    {
        array[i] = atoi(argv[i+1]);
    }

    //DIVIDE IT INTO TWO PARTS:
    int sizeOfAr1, sizeOfAr2, i = sizeOfAr1 = sizeOfAr2 = 0;
    int middle_elt = array[n / 2];
    while (i < n)
    {
        if (array[i] < middle_elt)
        {
            array1[sizeOfAr1] = array[i];
            sizeOfAr1++;
        }
        else
        {
            array2[sizeOfAr2] = array[i];
            sizeOfAr2++;
        }
        i++;
    }
    struct msg_buf myMsg;
    myMsg.mtype = 0;
    int msqid = msgget(IPC_PRIVATE, IPC_CREAT|0666);

    //STARTING TO PARALLELIZE
    int frk = fork();
    if (!frk) // CHILD
    {
        my_sort(array1, sizeOfAr1, 0, sizeOfAr1);
        myMsg.mtype = MAGIC_NUMBER;
        for(int i = 0; i<sizeOfAr1;i++)
        {
            myMsg.array_element = array1[i];
            msgsnd(msqid, &myMsg, sizeof(int), 0);
        }
        return 0;
    }
    else
    {
        my_sort(array2, sizeOfAr2, 0, sizeOfAr2);
        for(int j =0; j<sizeOfAr1;j++)
        {
            msgrcv(msqid, &myMsg, sizeof(int), MAGIC_NUMBER, 0);
            printf("%d ",myMsg.array_element);
        }
        for(int j =0; j<sizeOfAr2;j++)
        {
            printf("%d ",array2[j]);
        }
        printf("\n");
    }
    return 0;
}
Beispiel #21
0
int 
main( int nb_arg , char * tab_arg[] )
{     
     char nomprog[128] ;
     int file_id = 0;

    int i;

    message_t message;

    struct timeval temps ;
    double temps_debut;
    double temps_fin;

     /*-----*/

     if( nb_arg !=1 )
       {
	 fprintf( stderr , "%s - Emetteur dans la communication par paquet\n\n" , tab_arg[0] );
	 fprintf( stderr , "usage : %s \n" , tab_arg[0] );
	 exit(-1);
       }
     strcpy( nomprog , tab_arg[0] );

     /* Creation de la file de messages */
    if( ( file_id = msgget( CLE_BAL, IPC_CREAT | IPC_EXCL | 0666 )) == -1 )
    {
        perror("Probleme durant la creation de la file de messages");
        exit(-2);
    }


    /* Creation du message a envoyer */
    message.type = MSG_TYPE_RECEPTEUR;


    fprintf(stderr,  "\n---------- Debut emission %s ----------\n" , nomprog ) ;

    /* Recuperation de l'heure actuelle avec precision de l’ordre de la microseconde */
    gettimeofday(&temps, NULL);
    temps_debut = temps.tv_sec+(temps.tv_usec/1000000.0);


    /* Remplissage du message avec des Z */
    msg_remplir( &message , 'Z') ;


    /* Envoi de MESSAGES_NB messages dans la file de messages  */
    for(i=0; i<MESSAGES_NB; i++)
    {
        if( msgsnd( file_id, &message, sizeof(corps_t), 0) == -1)
        {
            perror ("Erreur durant l'envoi du message");
            exit(-3);
        }
    }

    /* Recuperation de l'heure actuelle avec precision de l’ordre de la microseconde */
    gettimeofday(&temps, NULL);
    temps_fin = temps.tv_sec+(temps.tv_usec/1000000.0);

    fprintf(stderr, "\nTemps d'emission           =  %.6lf secondes", temps_fin - temps_debut);
    fprintf(stderr, "\nTemps d'emission / message =  %.6lf secondes\n", (temps_fin - temps_debut) / MESSAGES_NB);
    fprintf(stderr, "\n----------- Fin emission %s -----------\n\n" , nomprog ) ;

     exit(0);
}
Beispiel #22
0
/*---------------------------------------------------------------------+
|                               main                                   |
| ==================================================================== |
|                                                                      |
| Function:  Main program  (see prolog for more details)               |
|                                                                      |
| Returns:   (0)  Successful completion                                |
|            (-1) Error occurred                                       |
|                                                                      |
+---------------------------------------------------------------------*/
int main (int argc, char **argv)
{
	struct msqid_ds info;	/* Message queue info */
	struct msgbuf buf;	/* Message queue buffer */
	int	mode = 0777;	/* Default mode bits */
	int	msqid;		/* Message queue identifier */
	size_t 	max_bytes;	/* Num bytes sent to message queue */
	size_t 	msg_size;	/* Num bytes sent to message queue */
	unsigned long	bytes_sent;	/* Num bytes sent to message queue */

	/*
	 * Parse command line options
	 */
	parse_args (argc, argv);
	if (logit) {
		if ((logfile = fopen (log_filename, "w")) == NULL)
			sys_error ("msgget failed", __LINE__);
	}

	/*
	 * Print out program header
	 */
	printf ("%s: IPC Message Queue TestSuite program\n\n", *argv);
	if (logit)
		fprintf (logfile, "%s: IPC Message Queue TestSuite program\n\n", *argv);

	/*
	 * Obtain a unique message queue identifier using msgget()
	 */
	if ((msqid = msgget (IPC_PRIVATE, IPC_CREAT|mode)) < 0)
		sys_error ("msgget failed", __LINE__);

	if (verbose)
		printf ("\tCreated message queue: %d\n\n", msqid);
	if (logit)
		fprintf (logfile, "\tCreated message queue: %d\n\n", msqid);


	/*
	 * Determine message queue limits
	 *
	 * Determine the maximum number of bytes that the message
	 * queue will hold.  Then determine the message size
	 * (Max num of bytes per queue / maximum num of messages per queue)
	 */
	if (msgctl (msqid, IPC_STAT, &info) < 0)
		sys_error ("msgctl (IPC_STAT) failed", __LINE__);

	max_bytes = info.msg_qbytes;

	/*
	 * this has been changed because of defect 227707 related to floating point
	 * problem, but here is not the right place to test floating point...
	 * msg_size  = (size_t) (0.5 + ((float) max_bytes / MAX_MSGS));
	 */
	msg_size  = (size_t)((max_bytes + MAX_MSGS - 1) / MAX_MSGS);

	if (verbose) {
		printf ("\tMax num of bytes per queue:  %ld\n", (long)max_bytes);
		printf ("\tMax messages per queue:      %d\n",  MAX_MSGS);
		printf ("\tCorresponding message size:  %ld\n\n", (long)msg_size);
	}
	if (logit) {
		fprintf (logfile, "\tMax num of bytes per queue:  %ld\n",  (long)max_bytes);
		fprintf (logfile, "\tMax messages per queue:      %d\n",  MAX_MSGS);
		fprintf (logfile, "\tCorresponding message size:  %ld\n\n", (long)msg_size);
	}

	/*
	 * Fill up the message queue
	 *
	 * Send bytes to the message queue until it fills up
	 */
	//	buf = (struct msgbuf *) calloc (msg_size + sizeof(struct msgbuf), sizeof (char));

	buf.mtype = 1L;

	bytes_sent = 0;
	while (bytes_sent < max_bytes - msg_size) {
		if (msgsnd (msqid, &buf, msg_size, 0) < 0)
			sys_error ("msgsnd failed", __LINE__);
		bytes_sent += msg_size;
		//usleep(5000);
		if (verbose) {
			printf ("\r\tBytes sent: %ld", (long)bytes_sent);
			fflush(stdout);
		  }
	}
	if (verbose) puts ("\n");
	if (logit) fprintf (logfile, "\tBytes sent: %ld\n", (long)bytes_sent);
	//free (buf);

	/*
	 * Remove the message queue
	 */
	if (msgctl (msqid, IPC_RMID, 0) < 0)
		sys_error ("msgctl (IPC_RMID) failed", __LINE__);
	if (verbose)
		printf ("\n\tRemoved message queue: %d\n", msqid);
	if (logit)
		fprintf (logfile, "\n\tRemoved message queue: %d\n", msqid);

	/* Program completed successfully -- exit */
	printf ("\nsuccessful!\n");
	if (logit) {
		fprintf (logfile, "\nsuccessful!\n");
		fclose (logfile);
	}


	return (0);
}
Beispiel #23
0
void answerForDoctorLoginRequest(int msgid, int msgrcv_size) {
    struct msgbuf doctor;
    msgrcv_size = msgrcv(msgid, &doctor, MSGBUF_SIZE , D_LOGIN_REQUEST, IPC_NOWAIT);
    if (msgrcv_size > 0) {
        if (fork() == 0) {
            int pid_registration = getpid();
            int pid_doctor = doctor.pid;
            doctor.typ = pid_doctor;
            doctor.pid = pid_registration;
            if (doctors_list_size > 0) {
                int i;
                for (i = 0; i < doctors_list_size; i++) {
                    bool appropriate = true;
                    int j;
                    // checking name
                    int name_size = strlen(doctors_list[i].name);
                    int name_size2 = strlen(doctor.name);
                    if (name_size != name_size2) appropriate = false;
                    if (!appropriate) continue;
                    for (j = 0; j < name_size; j++) {
                        if (doctor.name[j] != doctors_list[i].name[j]) {
                            appropriate = false;
                            break;
                        }
                    }
                    if (!appropriate) continue;
                    // checking surname
                    int surname_size = strlen(doctors_list[i].surname);
                    int surname_size2 = strlen(doctor.surname);
                    if (surname_size != surname_size2) appropriate = false;
                    if (!appropriate) continue;
                    for (j = 0; j < surname_size; j++) {
                        if (doctor.surname[j] != doctors_list[i].surname[j]) {
                            appropriate = false;
                            break;
                        }
                    }
                    if (!appropriate) continue;
                    // good name and surname:
                    int password_size = strlen(doctors_list[i].password);
                    int password_size2 = strlen(doctor.password);
                    if (password_size != password_size2) appropriate = false;
                    if (!appropriate) continue;
                    for (j = 0; j < password_size; j++) {
                        if (doctor.password[j] != doctors_list[i].password[j]) {
                            // wrong password
                            doctor.index = 1000;
                            msgsnd(msgid, &doctor, MSGBUF_SIZE, 0);
                            exit(pid_registration);
                            return;
                        }
                    }
                    // good name, surname and password
                    doctor = doctors_list[i];
                    doctor.typ = pid_doctor;
                    msgsnd(msgid, &doctor, MSGBUF_SIZE, 0);
                    exit(pid_registration);
                    return;
                }
            }
            // wrong pesel
            doctor.index = 1000;
            msgsnd(msgid, &doctor, MSGBUF_SIZE, 0);
            exit(pid_registration);
        }
    }
    return;
}
Beispiel #24
0
void
testaccess_ipc (int ipc_id, char opt, int mode, int expected, char *outbuf)
{
  int actual, semval, rc;
  int myerror = 0;
  char *chPtr;
  struct sembuf sop;
  uid_t tmpuid;
  gid_t tmpgid;
  struct msqbuf
  {
    long mtype;
    char mtext[80];
  } s_message, r_message;

  /* If we are root, we expect to succeed event
   * without explicit permission.
   */
  strcat (outbuf, (expected == -1) ? "expected: fail  " : "expected: pass  ");

  switch (opt)
    {
      /* Shared Memory */
    case 'm':
      /* Try to get (mode) access
       * There is no notion of a write-only shared memory
       * segment. We are testing READ ONLY and READWRITE access.
       */
      chPtr = shmat (ipc_id, NULL, (mode == O_RDONLY) ? SHM_RDONLY : 0);
      if (chPtr != (void *) -1)
{
  strcat (outbuf, "actual: pass ");
  actual = 0;
  if (shmdt (chPtr) == -1)
    {
      perror ("Warning: Could not dettach memory segment");
    }
}
      else
{
  myerror = errno;
  strcat (outbuf, "actual: fail ");
  actual = -1;
}
      break;
      /* Semaphores */
    case 's':
      tmpuid = geteuid ();
      tmpgid = getegid ();
      semval = semctl (ipc_id, 0, GETVAL);
      /* Need semaphore value == 0 to execute read permission test */
      if ((mode == O_RDONLY) && (semval > 0))
{
  setids (0, 0);
  if ((semctl (ipc_id, 0, SETVAL, 0)) == -1)
    {
      printf ("Unable to set semaphore value: %d\n", errno);
    }
  setids (tmpuid, tmpgid);
}
      /* Try to get mode access */
      sop.sem_num = 0;
      sop.sem_op = mode;
      sop.sem_flg = SEM_UNDO;
      actual = semop (ipc_id, &sop, 1);
      myerror = errno;
      if (actual != -1)
{
  strcat (outbuf, "actual: pass ");
  /* back to semaphore original value */
  if (mode != O_RDONLY)
    {
      sop.sem_op = -1;/* decrement semaphore */
      rc = semop (ipc_id, &sop, 1);
    }
}
      else
{
  /* Back to semaphore original value */
  if ((mode == O_RDONLY) && (semval > 0))
    {
      setids (0, 0);
      if ((semctl (ipc_id, 0, SETVAL, semval)) == -1)
{
  printf ("Unable to set semaphore " "value: %d\n", errno);
}
      setids (tmpuid, tmpgid);
    }
  strcat (outbuf, "actual: fail ");
}
      break;
      /* Message Queues */
    case 'q':
      tmpuid = geteuid ();
      tmpgid = getegid ();
      if (mode == O_RDONLY)
{
  setids (0, 0);
  /* Send a message to test msgrcv function */
  s_message.mtype = 1;
  memset (s_message.mtext, '\0', sizeof (s_message.mtext));
  strcpy (s_message.mtext, "First Message\0");
  if ((rc = msgsnd (ipc_id, &s_message,
    strlen (s_message.mtext), 0)) == -1)
    {
      printf ("Error sending first message: %d\n", errno);
    }
  setids (tmpuid, tmpgid);
}
      s_message.mtype = 1;
      memset (s_message.mtext, '\0', sizeof (s_message.mtext));
      strcpy (s_message.mtext, "Write Test\0");

      /* Try to get WRITE access */
      if (mode == O_WRONLY)
{
  actual = msgsnd (ipc_id, &s_message, strlen (s_message.mtext), 0);
}
      else
{
  /* Try to get READ access */
  actual = msgrcv (ipc_id, &r_message,
   sizeof (r_message.mtext), 0, IPC_NOWAIT);
}
      myerror = errno;
      if (actual != -1)
{
  strcat (outbuf, "actual: pass ");
}
      else
{
  strcat (outbuf, "actual: fail ");
}
      if (((mode == O_RDONLY) && (actual == -1)) ||
  ((mode == O_WRONLY) && (actual != -1)))
{
  setids (0, 0);
  /* discard the message send */
  rc = msgrcv (ipc_id, &r_message,
       sizeof (r_message.mtext), 0, IPC_NOWAIT);
  setids (tmpuid, tmpgid);
}
      break;
    }

  if ((actual == expected) || ((expected == 0) && (actual != -1)))
    {
      strcat (outbuf, "\tresult: PASS\n");
      totalpass++;
    }
  else
    {
      errno = myerror;// restore errno from correct error code
      sprintf (&(outbuf[strlen (outbuf)]), "\tresult: FAIL : "
       "errno = %d\n", errno);
      totalfail++;
    }
  printf ("%s", outbuf);
  return;
}
Beispiel #25
0
void answerForListOfVisits(int msgid, int msgrcv_size) {
    struct msgbuf visit, appointment;
    msgrcv_size = msgrcv(msgid, &visit, MSGBUF_SIZE , VISITS_REQUEST, IPC_NOWAIT);
    if (msgrcv_size > 0) {
        if (fork() == 0) {
            int pid_registration = getpid();
            int pid_patient = visit.pid;

            // SENDING ALL APPOINTMENTS
            int i;
            bool appropriate = false;
            for (i = 0; i < APPOINTMENTS_LIST_SIZE; i++) {
                int j;
                for (j = 0; j < 11; j++) {
                    if (appointments_list[i].pesel[j] != visit.pesel[j]) {
                        appropriate = false;
                        break;
                    }
                    appropriate = true;
                }
                if (appropriate && appointments_list[i].time_of_visit > 0) {
                    appointment = appointments_list[i];
                    appointment.typ = pid_patient;
                    msgsnd(msgid, &appointment, MSGBUF_SIZE, 0);
                }
            }
            appointment.index = 1000;
            appointment.pid = pid_registration;
            appointment.typ = pid_patient;
            msgsnd(msgid, &appointment, MSGBUF_SIZE, 0);

            // INFORMATION ABOUT ONE CHOSEN APPOINTMENT
            msgrcv(msgid, &visit, MSGBUF_SIZE , pid_registration, 0);
            pid_patient = visit.pid;
            if (visit.index == 1000) {   // resignation
                exit(pid_registration);
                return;
            }
            // choosing visit
            int number = visit.index;   // number of visit
            int counter = 0;
            for (i = 0; i < APPOINTMENTS_LIST_SIZE; i++) {
                appropriate = true;
                int j;
                for (j = 0; j < 11; j++) {
                    if (appointments_list[i].pesel[j] != visit.pesel[j]) {
                        appropriate = false;
                        break;
                    }
                }
                if (appropriate) {
                    //printf("//znalazłem ale nie wysłałem\n");
                    counter++;
                }
                if (appropriate && appointments_list[i].time_of_visit > 0 && counter == number) {
                    appointment = appointments_list[i];
                    appointment.typ = pid_patient;
                    msgsnd(msgid, &appointment, MSGBUF_SIZE, 0);
                    //printf("//wysłałem\n");
                    exit(pid_registration);
                    return;
                }
            }
            exit(pid_registration);
        }
    }
    return;
}
Beispiel #26
0
void try_msq()
{
	key_t key;
	int msqid;
	int childpid;
	char* message = "What the devil is this";
	struct msqdata md;
	struct msqid_ds msqinfo;

	get_key('q', &key);

	printf("------------ message queue------------\n");
	printf("creating message queue with key 0x%x\n", key);
	if((msqid = msgget(key, DEFAULT_FLAGS)) == -1) {
		perror("msgget");
		exit(1);
	}
	printf("created message queue of id %d\n\n", msqid);

	printf("sending message: [%s] of type [%d]\n", message, DEFAULT_MSG_TYPE);
	md.mtype = DEFAULT_MSG_TYPE;
	strcpy(md.mtext, message);
	if(msgsnd(msqid, &md, strlen(md.mtext)+1, 0) == -1) {
		perror("msgsnd");
		msgctl(msqid, IPC_RMID, 0);
		exit(1);
	}
	printf("sent message\n\n");

	if((childpid = fork()) == -1) {
		perror("fork");
		msgctl(msqid, IPC_RMID, 0);
		exit(1);
	} else if (!childpid) {
		printf("childpid [%d] in %d\n", getpid(), getppid());
		printf("reading message in child process\n");
		msgrcv(msqid, &md, MAX_MSG_SIZE, DEFAULT_MSG_TYPE, 0);
		printf("read message type: [%ld]\n"
			"read message data: [%s]\n\n",
			md.mtype, md.mtext);
	
		if((msqid = msgctl(msqid, MSG_STAT, &msqinfo)) == -1) {
			perror("msgctl");
			msgctl(msqid, IPC_RMID, 0);
			exit(1);
		}

		printf("current permissions %o\n", msqinfo.msg_perm.mode);
		printf("changing permissions\n");
		msqinfo.msg_perm.mode = 0664;
		msgctl(msqid, IPC_SET, &msqinfo);
		printf("current permissions %o\n\n", msqinfo.msg_perm.mode);

		message = "Hollowing is comming";
		printf("child sending message: [%s] of type [%d]\n", message, DEFAULT_MSG_TYPE);
		md.mtype = DEFAULT_MSG_TYPE;
		strcpy(md.mtext, message);
		if(msgsnd(msqid, &md, strlen(md.mtext)+1, 0) == -1) {
			perror("msgsnd");
			msgctl(msqid, IPC_RMID, 0);
			exit(1);
		}
		printf("sent message in child process\n\n");
	} else {
		wait(NULL);
		printf("This's parent process speaking\n");

		msgrcv(msqid, &md, MAX_MSG_SIZE, DEFAULT_MSG_TYPE, 0);
		printf("read message type: [%ld]\n"
			"read message data: [%s]\n\n",
			md.mtype, md.mtext);

		printf("removing message queue %d\n", msqid);
		if (msgctl(msqid, IPC_RMID, 0) == -1) 
			perror("msgctl, IPC_RMID");
		else 
			printf("removed message queue %d\n\n", msqid);
	}
}
Beispiel #27
0
void gra(int pokoj){

	int gameSend = msgget(pokoj*100, IPC_CREAT|0600);
	if(gameSend==-1){
		perror("Utworzenie kol. kom. wych. dla gry");
		exit(1);
	}


	int gameRcv = msgget(pokoj*100+10, IPC_CREAT|0600);
	if(gameRcv==-1){
		perror("Utworzenie kol. kom. przych. dla gry");
		exit(1);
	}

	srand(getpid()); //seedowanie liczb losowych wg id procesu

	int koniec=0;
	int tab[25];
	int gr[3][25]; //jakie karty ma jaki gracz
	int zdobyte[3][25]; //karty wygrane
	int kg[3]; //ile kart ma ktory gracz
	int i=0;
	int j=0;
	int pkty[3];
	for(i=0;i<3;i++)
			pkty[i]=0;
	int oferty[3];
	int pierwszy=0;
	while(!koniec){
		int koniecRozd=0;
		//rozdanie kart
		for(i=0;i<25;i++)tab[i]=1;
		for(i=0;i<25;i++)
			for(j=0;j<3;j++){
				zdobyte[j][i]=0;
				gr[j][i]=0;
		}
		for(i=0;i<3;i++)
			kg[i]=0;
		int rozdane=0;
		while(!koniecRozd){
			int karta=rand()%24 + 1;
			while(tab[karta]==0)karta=rand()%24 + 1;
			int ktory=rand()%3;
			if(kg[ktory]<7){
				gr[ktory][karta]=1;
				kg[ktory]+=1;
				tab[karta]=0;
				rozdane++;
			}
			if(rozdane==21)koniecRozd=1;
		}
		int musik[3];
		j=0;
		for(i=1;i<25;i++){
			if(tab[i]==1)musik[j++]=i;
		}
		//przesłanie info do graczy

		for(i=0;i<3;i++){
			buf->mtype=10+i+1;

			clearTab(buf->val, MAX);

			strcat(buf->val, "****************************************************************************************\nRozklad pkt:\nGracz 1: ");
			char* tmpS = malloc(sizeof(char)*4);
			clearTab(tmpS,4);
			sprintf(tmpS, "%d", pkty[0]);
			strcat(buf->val, tmpS);
			strcat(buf->val, "\nGracz 2: ");
			clearTab(tmpS,4);
			sprintf(tmpS, "%d", pkty[1]);
			strcat(buf->val, tmpS);
			strcat(buf->val, "\nGracz 3: ");
			clearTab(tmpS,4);
			sprintf(tmpS, "%d", pkty[2]);
			strcat(buf->val, tmpS);
			free(tmpS);
			char* tmp = malloc(sizeof(char)*MAX);
			jakieKarty(tmp,gr[i]);
			strcat(buf->val,"\n\nTwoje karty: ");
			strcat(buf->val, tmp);
			free(tmp);
			if(i==pierwszy)strcat(buf->val, "\nRozpoczynam licytacje, jako gracz na musiku, licytujesz 100");
			else strcat(buf->val,"\nRozpoczynam licytacje, czekam na oferty innych graczy...");
			buf->nr=buf->mtype-10;
			if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){
				perror("Wysylanie polecenia.");
				exit(1);
			}

		}
		//licytacja-----------------------------------------------------------------------------------------------------------------------------------
		printf("Pokoj %d: Licytacja\n",pokoj);
		oferty[0]=1;
		oferty[1]=1;
		oferty[2]=1;

			if(oferty[pierwszy]==1){
				char str[2];
				clearTab(str, 2);
				clearTab(buf->val, MAX);
				buf->mtype=11+(pierwszy+1)%3;
				buf->nr=buf->mtype-10;
				oferty[pierwszy]=100;
				strcat(buf->val, "\nRozpoczynam licytacje, podaj ilosc pktow. (0 == pas)\n\tGracz ");
				sprintf(str, "%d", (pierwszy+1));
				strcat(buf->val, str);
				strcat(buf->val, ": 100");
				if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){ //wysłanie oferty do drugiego gracza
					perror("Wysylanie polecenia.");
					exit(1);
				}
			}

			if(msgrcv(gameRcv, buf, (sizeof(struct mybuf)-sizeof(long)), 101+(pierwszy+1)%3, 0) != -1){ //odebranie od drugiego gracza
				char str[4];
				char str2[4];
				strcpy(str, buf->val);
				clearTab(buf->val, MAX);
				oferty[(pierwszy+1)%3]=atoi(str);
				if(oferty[(pierwszy+1)%3] > 360){
					oferty[(pierwszy+1)%3]=360;
				}
				buf->mtype=11+(pierwszy+2)%3;
				buf->nr=buf->mtype-10;
				strcat(buf->val, "\nRozpoczynam licytacje, podaj ilosc pktow. (0 == pas)\n\tGracz ");
				sprintf(str2, "%d", (pierwszy+1));
				strcat(buf->val, str2);
				strcat(buf->val, ": 100");
				strcat(buf->val, "\n\tGracz ");
				sprintf(str2, "%d", (pierwszy+1)%3 + 1);
				strcat(buf->val, str2);
				strcat(buf->val, ": ");
				strcat(buf->val, str);
				if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){ //wysłanie ofert do ostatneigo gracza
					perror("Wysylanie polecenia.");
					exit(1);
				}
			}

			if(msgrcv(gameRcv, buf, (sizeof(struct mybuf)-sizeof(long)), 101+(pierwszy+2)%3, 0) != -1){ //odebranie od ostatniego gracza
				char str[4];
				strcpy(str, buf->val);
				oferty[(pierwszy+2)%3]=atoi(str);
				if(oferty[(pierwszy+2)%3] > 360){
					oferty[(pierwszy+2)%3]=0;
				}
			}

		int wygryw=0;
		for(i=1;i<3;i++){
			if(oferty[i]>oferty[wygryw])wygryw=i;

		}
		int koniecLic=0;
		if(oferty[(wygryw+1)%3]<=0 && oferty[(wygryw+2)%3]<=0)koniecLic=1; //jezeli tylko jedna osoba nie spasowala
		int kto=pierwszy;

		while(!koniecLic){
			clearTab(buf->val, MAX);
			if(oferty[kto]!=0){
				char str[4];
				sprintf(str, "%d",oferty[wygryw]);
				strcat(buf->val,"Max oferta: ");
				strcat(buf->val, str);
				strcat(buf->val, " (Gracz ");
				clearTab(str,4);
				sprintf(str, "%d", (wygryw+1));
				strcat(buf->val, str);
				strcat(buf->val, ")\nPodaj wyzsza oferte (lub 0 by spasowac): ");

				buf->mtype=10+kto+1;
				buf->nr=buf->mtype-10;
				if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){ //wysłanie informacji
					perror("Wysylanie polecenia.");
					exit(1);
				}
				if(msgrcv(gameRcv, buf, (sizeof(struct mybuf)-sizeof(long)), (100+kto+1), 0) != -1){ //odebranie od trzeciego gracza
					char str[4];
					strcpy(str, buf->val);
					oferty[kto]=atoi(str);
					if(oferty[kto] > 360 || oferty[kto] == oferty[wygryw]){
						oferty[kto]=0;
					}
					if(oferty[kto]>oferty[wygryw])wygryw=kto;
					else if(oferty[(wygryw+1)%3]<=0 && oferty[(wygryw+2)%3]<=0)koniecLic=1;
				}
			}
			kto=(kto+1)%3;

		}
		printf("Pokoj %d: Licytacje wygral Gracz %d\n",pokoj, (wygryw+1));

		for(i=0;i<3;i++) //dodanie kart z musika do puli gracza, kt wygral licytacje
			gr[wygryw][musik[i]]=1;

		clearTab(buf->val, MAX);
		buf->mtype=11+wygryw;
		buf->nr=buf->mtype-10;
		strcat(buf->val, "Wygrales licytacje! Musik: ");
		char str[11];
		sprintf(str, "%d %d %d", musik[0], musik[1], musik[2]);
		strcat(buf->val, str);
		char* tmp = malloc(sizeof(char)*MAX);
		jakieKarty(tmp,gr[wygryw]);
		strcat(buf->val,"\nTwoje karty: ");
		strcat(buf->val, tmp);
		free(tmp);//
		strcat(buf->val, "\nPodaj dwie karty do oddania i ostateczna kwote ktora planujesz ugrac(x y z): ");
		if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){ //wysłanie informacji do wygranego
				perror("Wysylanie polecenia.");
				exit(1);
		}
		if(msgrcv(gameRcv, buf, (sizeof(struct mybuf)-sizeof(long)), (101+wygryw), 0) != -1){
			char str2[4];
			char str3[10];
			char str4[4];
			clearTab(str2,4);
			clearTab(str3,11);
			clearTab(str4,4);
			strcpy(str3, str);
			strcpy(str, buf->val);
			clearTab(buf->val, MAX);
			strcat(buf->val, "Musik: ");
			strcat(buf->val, str3);
			copyNthNumber(str2, str, 1, 11); //kopiuj pierwsza podana liczbe
			gr[wygryw][atoi(str2)]=0;
			strcat(buf->val,"\nOtrzymana karta: ");
			strcat(buf->val, str2);
			copyNthNumber(str4, str, 3, 11); //kopiuj ewentualnie podana kwote do licytacji
			int przebita = atoi(str4);
			strcat(buf->val, "\nLiczba pktow zadeklarowana do ugrania przez Gracza ");

			if(przebita<oferty[wygryw] || przebita > 360){
				clearTab(str4, 4);
				sprintf(str4, "%d", oferty[wygryw]);
			}
			strcat(buf->val, str4);

			buf->mtype=11+(wygryw+1)%3;
			gr[(wygryw+1)%3][atoi(str2)]=1;


			buf->nr=buf->mtype-10;
			if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){ //wysłanie informacji do pozostalych graczy
				perror("Wysylanie polecenia.");
				exit(1);
			}

			clearTab(buf->val, MAX);
			clearTab(str2, 4);
			strcat(buf->val, "Musik: ");
			strcat(buf->val, str3);
			copyNthNumber(str2, str, 2, 11); //kopiuj druga z podanych liczb
			gr[wygryw][atoi(str2)]=0;
			strcat(buf->val,"\nOtrzymana karta: ");
			strcat(buf->val, str2);
			strcat(buf->val, "\nLiczba pktow zadeklarowana do ugrania przez Gracza ");
			if(przebita<oferty[wygryw]){
				clearTab(str4, 4);
				sprintf(str4, "%d", oferty[wygryw]);
			}
			strcat(buf->val, str4);

			buf->mtype=11+(wygryw+2)%3;
			gr[(wygryw+2)%3][atoi(str2)]=1;

			buf->nr=buf->mtype-10;
			if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){ //wysłanie informacji do pozostalych graczy
				perror("Wysylanie polecenia.");
				exit(1);
			}
		}

		//rozgrywka----------------------------------------------------------------------------------------------------------------------------
		printf("Pokoj %d: Rozgrywka\n", pokoj);
		int rozp=wygryw;
		int odbior;
		int meld[3];
		meld[0]=0;
		meld[1]=0;
		meld[2]=0;
		int atut=-1;

		for(i=0;i<8;i++){ //8 tur

			printf("Pokoj %d: %d tura\n",pokoj, (i+1));
			int kar=0, kar2=0, kar3=0, kolor=-1, m=0, najwiek=0;

			char str123[4];
			clearTab(buf->val, MAX);
			char* tmp = malloc(sizeof(char)*MAX);
			jakieKarty(tmp,gr[rozp]);
			strcat(buf->val,"--------------------------------------------\nKarty: ");
			strcat(buf->val, tmp);
			if(atut==-1)strcat(buf->val, "\nPodaj numer karty do zagrania (mozna meldowac, jezeli ma sie pare na rece): ");
			else{
				strcat(buf->val, "\nPodaj numer karty do zagrania (mozna meldowac, jezeli ma sie pare na rece; atut: X%4==");
				char st[2];
				sprintf(st, "%d", atut);
				strcat(buf->val, st);
				strcat(buf->val, "): ");
			}

			buf->mtype=10+rozp+1;
			buf->nr=buf->mtype-10;
			printf("Pokoj %d: wysylam na %d\n",pokoj,buf->mtype);
			if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), IPC_NOWAIT) == -1){ //wys. info. o kartach i prosba o karte
				perror("Wysylanie polecenia.");
				exit(1);
			}

			sleep(1);
			clearTab(buf->val, MAX);
			printf("Pokoj %d: czekam na karte gracza %d\n",pokoj, (rozp+1));
			if(msgrcv(gameRcv, buf, (sizeof(struct mybuf)-sizeof(long)), (100+rozp+1), 0) != -1){
				if(buf->val[0]=='m' && buf->val[1]!=NULL && buf->val[1]!='\n'){ //jezeli byl meldunek
					char kol[3];
					clearTab(kol,3);
					kol[0]=buf->val[1];
					kol[1]=buf->val[2];
					printf("Pokoj %d: gracz %d zagrywa %s\n",pokoj, rozp, kol);
					kar = atoi(kol);
					if(kar<1 || kar>24 gr[odbior-101][kar3]==0) kar = najwKarta(gr[rozp]);
					gr[rozp][kar]=0;
					kolor = kar%4;
					if(kar>8 && kar<13 && gr[rozp][kar+4]==1){
						switch(kolor){
							case 0:
								printf("Pokoj %d: Gracz %d zameldowal 40\n",pokoj, (rozp+1));
								meld[rozp]+=40;
								atut=0;
								break;
							case 1:
								printf("Pokoj %d: Gracz %d zameldowal 60\n",pokoj, (rozp+1));
								meld[rozp]+=60;
								atut=1;
								break;
							case 2:
								printf("Pokoj %d: Gracz %d zameldowal 80\n",pokoj, (rozp+1));
								meld[rozp]+=80;
								atut=2;
								break;
							default:
								printf("Pokoj %d: Gracz %d zameldowal 100\n",pokoj, (rozp+1));
								meld[rozp]+=100;
								atut=3;
								break;
						}
						clearTab(str123, 4);
						strcat(str123, kol);

						m=1;
					}
					else {
						kar=0; //jak ktos probuje meldowac niemajac pary, karta jest bezuzyteczna
						printf("\t\tbufor: %s\n", buf->val);
					}
					usleep(10);
				}
				else{
					usleep(10);
					clearTab(str123,4);
					strcat(str123, buf->val);
					printf("Pokoj %d: gracz %d zagrywa %s\n",pokoj, rozp, str123);
					kar = atoi(str123);
					if(kar<1 || kar>24 gr[rozp][kar]==0) kar = najwKarta(gr[rozp]);
					gr[rozp][kar]=0;
					kolor = kar%4;
				}

				najwiek=rozp;
			}

			buf->mtype=11+(rozp+1)%3;
			odbior = 101+(rozp+1)%3;

			clearTab(buf->val, MAX);
			clearTab(tmp, MAX);
			jakieKarty(tmp,gr[odbior-101]);
			strcat(buf->val,"--------------------------------------------\nKarty: ");
			strcat(buf->val, tmp);
			strcat(buf->val, "\nKarta zagrana: ");


			if(m==1)strcat(buf->val, "m");
			strcat(buf->val, str123);
			if(atut==-1)strcat(buf->val, "\nPodaj numer karty do zagrania: ");
			else{
				strcat(buf->val, "\nPodaj numer karty do zagrania (atut: X%4==");
				char st[2];
				sprintf(st, "%d", atut);
				strcat(buf->val, st);
				strcat(buf->val, "): ");
			}

			//wys. info. o kartach i prosba o karte do gracza po lewej
			printf("Pokoj %d: wysylam na %d\n",pokoj,buf->mtype);
			buf->nr=buf->mtype-10;
			if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), IPC_NOWAIT) == -1){
				perror("Wysylanie polecenia.");
				exit(1);
			}

			sleep(1);
			clearTab(buf->val,MAX);
			printf("Pokoj %d: czekam na karte gracza %d\n", pokoj,(odbior-100));
			if(msgrcv(gameRcv, buf, (sizeof(struct mybuf)-sizeof(long)), odbior, 0) != -1){
				clearTab(str123,4);
				strcat(str123, buf->val);
				printf("Pokoj %d: gracz %d zagrywa %s\n",pokoj, odbior-101, str123);
				kar2 = atoi(str123);
				if(kar2<1 || kar2>24 || gr[odbior-101][kar2]==0) {
					printf("Pokoj %d: gracz %d - proba oszustwa\n",pokoj, odbior-101);
					kar2 = najwKarta(gr[odbior-101]);
				}
				gr[odbior-101][kar2]=0;
				if((kolor==(kar2%4) && kar2>kar) || (kolor!=atut && atut==(kar2%4)))
					najwiek = odbior-101;
				if(kolor!=atut && atut==(kar2%4))
					kolor=atut;
			}

			buf->mtype=11+(rozp+2)%3;
			odbior = 101+(rozp+2)%3;


			clearTab(buf->val, MAX);
			clearTab(tmp, MAX);
			jakieKarty(tmp,gr[odbior-101]);
			strcat(buf->val,"--------------------------------------------\nKarty: ");
			strcat(buf->val, tmp);
			strcat(buf->val, "\nKarty zagrane: ");


			if(m==1)strcat(buf->val, "m");
			clearTab(str123, 4);
			sprintf(str123, "%d ", kar);
			strcat(buf->val, str123);
			sprintf(str123, "%d ", kar2);
			strcat(buf->val, str123);
			if(atut==-1)strcat(buf->val, "\nPodaj numer karty do zagrania: ");
			else{
				strcat(buf->val, "\nPodaj numer karty do zagrania (atut: X%4==");
				char st[2];
				sprintf(st, "%d", atut);
				strcat(buf->val, st);
				strcat(buf->val, "): ");
			}

			//wys. info. o kartach i prosba o karte do ostatniego gracza
			printf("Pokoj %d: wysylam na %d\n",pokoj,buf->mtype);
			buf->nr=buf->mtype-10;
			if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){ //wys. info. o kartach i prosba o karte
				perror("Wysylanie polecenia.");
				exit(1);
			}

			sleep(1);

			printf("Pokoj %d: czekam na karte gracza %d\n",pokoj, (odbior-100));
			if(msgrcv(gameRcv, buf, (sizeof(struct mybuf)-sizeof(long)), odbior, 0) != -1){
				clearTab(str123,4);
				strcat(str123, buf->val);
				printf("Pokoj %d: gracz %d zagrywa %s\n",pokoj, odbior-101, str123);
				kar3 = atoi(str123);
				if(kar3<1 || kar3>24 || gr[odbior-101][kar3]==0) {
					printf("Pokoj %d: gracz %d - proba oszustwa\n",pokoj, odbior-101);
					kar3 = najwKarta(gr[odbior-101]);
				}
				gr[odbior-101][kar3]=0;
				//wygrana jeśli: karty tego samego koloru a ta najwieksza; jedyna karta atutowa; wieksza z kart atutowych
				if((kolor==(kar3%4) && ((najwiek==rozp && kar3>kar) || (najwiek!=rozp && kar3>kar2))) ||
				  	(atut==(kar3%4) && kolor!=atut) ||
				    (atut==(kar3%4) && ((najwiek==rozp && kolor==atut && kar3>kar) || (najwiek!=rozp && kar2%4==atut && kar3>kar2)))){
					najwiek = odbior-101;
				}
			}

			clearTab(buf->val, MAX);
			clearTab(str123, 4);
			strcat(buf->val, "Wygrywa gracz ");
			sprintf(str123, "%d ",(najwiek+1));
			strcat(buf->val, str123);
			clearTab(str123, 4);
			strcat(buf->val, "\nKarty zagrane w tej turze: ");
			sprintf(str123, "%d ", kar);
			strcat(buf->val, str123);
			sprintf(str123, "%d ", kar2);
			strcat(buf->val, str123);
			sprintf(str123, "%d ", kar3);
			strcat(buf->val, str123);
			if(i<7)strcat(buf->val, "\n\nKolejna tura!");
			else strcat(buf->val, "\n\nPodliczanie pktow!");

			for(j=0;j<3;j++){
				buf->mtype=10+j+1;
				buf->nr=buf->mtype-10;
				if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){ //wys. info. o rezultacie
					perror("Wysylanie polecenia.");
					exit(1);
				}
			}

			zdobyte[najwiek][kar]=1;
			zdobyte[najwiek][kar2]=1;
			zdobyte[najwiek][kar3]=1;
			free(tmp);
			rozp=najwiek;
		}
		for(i=0;i<3;i++){
			int tmpPkt=liczPkt(zdobyte[i]) + meld[i];
			if(i!=wygryw){
				int przyb = tmpPkt/5;
				if(przyb%2 == 1) przyb++;
				pkty[i]+=przyb*5;
			}
			else if(i==wygryw && tmpPkt >= oferty[wygryw])
				pkty[i]+=oferty[wygryw];
			else if(i==wygryw && tmpPkt < oferty[wygryw])
				pkty[i]-=oferty[wygryw];
			printf("Pokoj %d: Gracz %d: %d\n", pokoj, (i+1), (tmpPkt));
			if(pkty[i]>=WYGRANA)koniec=1;
		}
		pierwszy=(pierwszy+1)%3;
	}
	printf("Pokoj %d: Podsumanie zakonczonej gry\n", pokoj);
	clearTab(buf->val, MAX);
	strcat(buf->val, "Koniec gry!\n");
	strcat(buf->val, "Ostateczny rozklad pkt:\nGracz 1: ");
	char* tmpS = malloc(sizeof(char)*4);
	clearTab(tmpS,4);
	sprintf(tmpS, "%d", pkty[0]);
	strcat(buf->val, tmpS);
	strcat(buf->val, "\nGracz 2: ");
	clearTab(tmpS,4);
	sprintf(tmpS, "%d", pkty[1]);
	strcat(buf->val, tmpS);
	strcat(buf->val, "\nGracz 3: ");
	clearTab(tmpS,4);
	sprintf(tmpS, "%d", pkty[2]);
	strcat(buf->val, tmpS);
	free(tmpS);

	for(i=0;i<3;i++){
		buf->mtype=10+i+1;
		printf("Pokoj %d: koniec dla %d\n", pokoj,(i+1));
		buf->nr=0;
		if(msgsnd(gameSend, buf, (sizeof(struct mybuf)-sizeof(long)), 0) == -1){ //wys. info. o rezultacie
			perror("Wysylanie polecenia.");
			exit(1);
		}
	}
}
Beispiel #28
0
main() {

        signal(SIGINT,acabou);

        // ligar ao semáforo
        int semid = semget(73452, 1, 0);
        exit_on_error(semid, "semget");

        // ligar à memória partilhada
        int id_mem = shmget(73452, 500 * sizeof(Tcondutor), 0);
        exit_on_error(id_mem, "shmget");
        printf("Ligado à memória\n");

        // Erro do ponteiro
        Tcondutor *p = shmat(id_mem, 0, 0);
        exit_on_null(p, "shmat");

        // input do número do condutor
        char num_aluno[100];
        printf("Número de condutor: ");
        fgets(num_aluno, 100, stdin);
        n = atoi (num_aluno);

        // percorrer a memória partilhada de 500 pos
        // se o número da memória é igual ao inserido
        int i;
        printf("Número inserido: %d\n", n);

        down(semid); // down do semáforo
        for(i = 0; i < 500; i++) {
                if( n == p[i].num_aluno) {
                        p[i].activo = 1; // ativar o condutor
                        printf("Condutor ativo\n");
                        p[i].disponivel_desde = time(NULL); // data atual
                        p[i].PID = getpid(); // o seu PID
  printf("Já és condutor: %s\nA tua matrícula é: %s\n", p[i].nome,p[i].matricula);
                break;
                }
        }
        up(semid); // up do semáforo


        // ligar à fila de mensagens
        int id_msg = msgget(96975, 0);
        exit_on_error(id_msg, "Erro no msgget");
        printf("Ligado à fila\n");

        // ao receber a mensagem 2
        MsgCorrida m;
        while(1) {

                // recebe mensagem 2 do tipo pid
                int status = msgrcv(id_msg, &m, sizeof(m.dados), getpid(), 0);
                exit_on_error(status, "Erro ao receber mensagem 2");
                printf("Mensagem 2 recebida\n");

                // imprimir o pid do passageiro
                printf("O PID do passageiro é: %d\n", m.dados.pid_passageiro);

                // enviar a mensagem 3
                char local[100];
                m.tipo = m.dados.pid_passageiro; // tipo com o PID do passageiro
                m.dados.pid_condutor = getpid(); // PID do condutor com o meu PID
                printf("Meu PID: %d\n", getpid()); // confirmar o meu pid com o Admin e o Passageiro
                printf("Minha localização: ");
                fgets(local, 100, stdin); // minha localização
                local[ strlen(local) - 1 ] = '\0';

                status = msgsnd(id_msg, &m, sizeof(m.dados), 0);
                exit_on_error(status, "Erro ao enviar mensagem 3");
                printf("Mensagem 3 enviada\n");

                // espera de 1-20s
                srand(time(NULL));
                sleep(rand() %20 + 1);

                // pede o valor da corrida
                char val[10];
                printf("Valor da corrida: ");
                fgets(val, 10, stdin);
                val[ strlen(val) - 1 ] = '\0';

                // enviar mensagem 4 com recibo
                m.tipo = 1;
 		m.dados.pid_passageiro = m.dados.pid_passageiro;
                strcpy(m.dados.local_encontro, local);
                m.dados.valor = atof(val);

                status = msgsnd(id_msg, &m, sizeof(m.dados), 0);
                exit_on_error(status, "Erro ao enviar mensagem 4");
                printf("Mensagem 4 enviada\n");
        }

        acabou(SIGINT); // Sinal do Ctrl C
}
Beispiel #29
0
int main(int argc, char **argv){
	if(argc < 6 || argc > 7){
		printf("Wrong number of arguments!");
		exit(-1);
	}
	
	int workerID = str2int(argv[1]);
	int nBuffers = str2int(argv[2]);
	float sleepTime = str2float(argv[3]);
	int msgID = str2int(argv[4]);
	int shmID = str2int(argv[5]);
	int semID;
	BOOL lock = FALSE;
	if(argc == 7){ //if a semID is given
		semID = str2int(argv[6]);
		lock = TRUE;
	}

	//connect to message queue
	int msgQ = msgID;
	if(msgQ == -1){
		perror("Error connecting to message queue");
		exit(-1);
	}

	//send startup message
	struct message msg;
	msg.mtype = 1;
	msg.workerID = workerID;
	msg.sleepTime = sleepTime;

	if(msgsnd(msgQ, &msg, sizeof(struct message) - sizeof(long), 0) == -1){
		perror("Error sending message");
		exit(-1);
	}

	//attatch to shared memory
	int *shm = shmat(shmID, (void *)0, 0);
	if(shm == (int *) -1){
		perror("Error attatching to shared memory");
		exit(-1);
	}
	
	//===================== PART 5 ==============================
	
	//use semaphores
	if(lock){
		int i;
		int currentBuffer = workerID;
		for(i=0; i<nBuffers; i++){
			int j;
	
			for(j=0; j<2; j++){ //read twice
				wait(currentBuffer, semID, nBuffers);
		
				int read = shm[currentBuffer];
	
				if(usleep(sleepTime*1000000) == -1){
					perror("Error sleeping");
					exit(-1);
				}
	
				//check if changed
				if(shm[currentBuffer] != read){
					msg.mtype = 3;
					msg.workerID = workerID;
					msg.changedBuffer = currentBuffer;
					msg.initVal = read;
					msg.newVal = shm[currentBuffer];
					if(msgsnd(msgQ, &msg, sizeof(struct message), 0) == -1){
						perror("Error sending message");
						exit(-1);
					}
				}

				signal(currentBuffer, semID, nBuffers);
		
				currentBuffer += workerID;
				if(currentBuffer >= nBuffers)
					currentBuffer -= nBuffers;
			}
	
			//write
			wait(currentBuffer, semID, nBuffers);

			int read = shm[currentBuffer];
	
			if(usleep(sleepTime*1000000) == -1){
				perror("Error sleeping");
				exit(-1);
			}
			
			shm[currentBuffer] = read | (1<<(workerID -1));

			signal(currentBuffer, semID, nBuffers);
	
			currentBuffer += workerID;
			if(currentBuffer >= nBuffers)
				currentBuffer -= nBuffers;
	
		}
	}

	//===================== PART 3/4 ============================

	//dont use semaphores
	else{	
		int i;
		int currentBuffer = workerID;
		for(i=0; i<nBuffers; i++){
			int j;

			for(j=0; j<2; j++){ //read twice
				int read = shm[currentBuffer];
	
				if(usleep(sleepTime*1000000) == -1){
					perror("Error sleeping");
					exit(-1);
				}
	
				//check if changed
				if(shm[currentBuffer] != read){
					msg.mtype = 3;
					msg.workerID = workerID;
					msg.changedBuffer = currentBuffer;
					msg.initVal = read;
					msg.newVal = shm[currentBuffer];
					if(msgsnd(msgQ, &msg, sizeof(struct message), 0) == -1){
						perror("Error sending message");
						exit(-1);
					}
				}
				
				currentBuffer += workerID;
				if(currentBuffer >= nBuffers)
					currentBuffer -= nBuffers;
			}
	
			//write
			int read = shm[currentBuffer];
	
			if(usleep(sleepTime*1000000) == -1){
				perror("Error sleeping");
				exit(-1);
			}
			
			shm[currentBuffer] = read | (1<<(workerID -1));
	
			currentBuffer += workerID;
			if(currentBuffer >= nBuffers)
				currentBuffer -= nBuffers;
	
		}
	}
	
	//cleanup message
	msg.mtype = 2;
	msg.workerID = workerID;
	if(msgsnd(msgQ, &msg, sizeof(struct message), 0) == -1){
		perror("Error sending message");
		exit(-1);
	}

	exit(0);
}
int mib_get_8186( unsigned long id, void *data, unsigned long data_len )
{
	/* 
	 * NOTE: It will get NOTHING, if one uses this function to 
	 * retrieve MIB_VOIP_CFG due to apmib_get() ignore this ID. 
	 */
	union {
		VoipFlashWriteMsg_t msgSuper;
		VoipFlashWriteMsgMibGet_t msgMibget;
		VoipFlashWriteMsgMibGetAck_t msgMibgetAck;
	} sh;
	unsigned long offset = 0, len = data_len, cur_len;

	if( data_len > MAX_MIBMSG_LENGTH ) {
		printf( "mib_get give a too large data_len(%ld>%d)\n", data_len, MAX_MIBMSG_LENGTH );
		return 0;
	}
	
	while( len ) {
	
		cur_len = ( len >= MAX_MIBMSG_ATOM ? MAX_MIBMSG_ATOM : len );
		len -= cur_len;		
		
		/* fill payload */
		sh.msgMibget.type = VFWM_CMD_MIBGET;
		sh.msgMibget.len = VFWM_PAYLOAD_SIZE( sh.msgMibget ) - sizeof( sh.msgMibget.len );
		sh.msgMibget.cid = cidVoipFlashClientWriteRcv;
		sh.msgMibget.data_id = id;
		sh.msgMibget.data_len = data_len;
		sh.msgMibget.data_offset = offset;
	
		/* send */
		msgsnd( qidVoipFlashClientWriteSnd, &sh.msgMibget, VFWM_PAYLOAD_SIZE( sh.msgMibget ), 0 );
	
		/* wait for ack */
		while( 1 ) {
			if( msgrcv( qidVoipFlashClientWriteRcv, &sh.msgSuper, VFWM_PAYLOAD_SIZE( sh.msgSuper ), 0, 0 ) < 0 )
			{
				if( /* bIgnoreIntr && */ errno == EINTR )	/* the process caught a signal */
					continue;
				else {	/* TODO: how to deal with other error?? */
					printf( "Rcv va error!!!(%d)\n", errno );
					break;
				}
			} else
				break;
		}
		
		if( sh.msgMibgetAck.type == VFWM_CMD_MIBGET_ACK ) {
			printf( "Rcv mib_get ack\n" );
	
			/* copy data from server's ack */
			memcpy( ( unsigned char * )data + ( offset << MAX_MIBMSG_ORDER ), 
					sh.msgMibgetAck.data, 
					cur_len );
		} else {
			printf( "Not mib_get ack. %ld\n", sh.msgMibgetAck.type );
			
			return 0;
		}
		
		offset ++;
	}

	return sh.msgMibgetAck.result;
}