// Обработчик #PF void pf_handler(uint address, uint errcode) { // printf_color(0x04, "Page Fault: addr=0x%x, errcode=0x%x\n", address, errcode); ulong ok = 0; TaskStruct *task = Task[Current]; // Младшый бит errcode определяет, было ли вызвано // исключение отсутствующей страницей (0) или нарушением // привелегий if ((errcode & 1) == 0) { if (BinFormats[task->BinFormat].load_page) // Функция возвратит физический адрес новой страницы, А ТАКЖЕ ФЛАГИ для этой записи // в таблице страниц ok = BinFormats[task->BinFormat].load_page(address); } else { printf_color(0x04, "Strange #PF errcode=0x%x (pid=%d)\n", errcode, Task[Current]->pid); } if (! ok) { printf_color(0x04, "Process requested an invalid page (req addr=0x%x)! Killing him...\n", address); scheduler_kill_current(); } else map_page(ok, Task[Current], address, ok & PA_MASK); }
/* Defines the used database. */ void command_use(cli_t *cli, char *pt) { int rc; // check connection if needed if (!check_connection(cli)) return; // request if (!strlen(pt) || !strcasecmp(pt, "default")) { // use default database if ((rc = finedb_setdb(cli->finedb, NULL)) != 0) { printf_color("red", "Unable to use the default database (%d).", rc); printf("\n"); } else { YFREE(cli->dbname); printf_decorated("faint", "Use the default database"); printf("\n"); } } else { // set a new database if ((rc = finedb_setdb(cli->finedb, pt)) != 0) { printf_color("red", "Unable to use the '%s' database (%d).", rc); printf("\n"); } else { YFREE(cli->dbname); cli->dbname = strdup(pt); printf_decorated("faint", "Use the '%s' database", pt); printf("\n"); } } }
void ls(char *path) { char buf[512], *p; int fd; struct dirent de; struct stat st; if((fd = open(path, 0)) < 0) { printf(2, "ls: cannot open %s\n", path); return; } if(fstat(fd, &st) < 0) { printf(2, "ls: cannot stat %s\n", path); close(fd); return; } switch(st.type) { case T_FILE: printf(1, "%s %d %d %d\n", fmtname(path), st.type, st.ino, st.size); break; case T_DIR: if(strlen(path) + 1 + DIRSIZ + 1 > sizeof buf) { printf(1, "ls: path too long\n"); break; } strcpy(buf, path); p = buf + strlen(buf); *p++ = '/'; while(read(fd, &de, sizeof(de)) == sizeof(de)) { if(de.inum == 0) { continue; } memmove(p, de.name, DIRSIZ); p[DIRSIZ] = 0; if(stat(buf, &st) < 0) { printf(1, "ls: cannot stat %s\n", buf); continue; } if(st.type == T_DIR && strcmp(p, ".") != 0 && strcmp(p, "..") != 0) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size); } else if(st.type == T_DEV) { printf_color(COLOR_BLACK, COLOR_YELLOW, true, 1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size); } else { printf(1, "%s %d %d %d\n", fmtname(buf), st.type, st.ino, st.size); } } break; } close(fd); }
// Системный вызов syscall_exit // Его вызывает пользовательский процесс когда завершается uint syscall_exit(uint exitcode) { printf_color(0x04, "Process %d exits with code %d\n", Task[Current]->pid, exitcode); scheduler_kill_current(); return 0; }
// Иницилизация контроллера и драйвера void fd_init() { puts_color("Starting FD driver...", 0x0b); #if (CFG_FD_READ_CACHE == 1) // Иницилизируем кольцевую кэш-очередь uint i; for (i = 0; i < CFG_FD_READ_CACHE_SIZE; i++) fd_cache[i].LBA = -1; fd_cache_pos = 0; printf_color(0x0a, "\t\t%dKb sector cache\n", CFG_FD_READ_CACHE_SIZE/2); #else puts_color(0x0a, "\tno sector cache\n"); #endif fd_clear_int_flag(); out_DOR(0x1c); // Включаем двигатель первого привода fd_wait_for_RQM(); // Посылаем команду Иницилизация out_FIFO(0x07); out_FIFO(0x00); //fd_wait_for_RQM(); fd_wait_for_int(); out_FIFO(0x08); // Посылаем комадну Sense Interrupt Status uchar ST0; ST0 = in_FIFO(); // И считываем ее результат: ST0 и PCN in_FIFO(); }
uint syscall_bin_load(char *filename, char *arg) { char localbuf[256]; char locarg[256]; strncpy_from_user(localbuf, filename, 256); strncpy_from_user(locarg, arg, 256); uint pid = bin_load_bin(localbuf, locarg); if (pid == (uint)-1) printf_color(0x04, "Cannot load binary\n"); return pid; }
/* Start a transaction. */ void command_start(cli_t *cli) { int rc; // check connection if needed if (!check_connection(cli)) return; // check opened transaction if (cli->in_transaction) { printf_color("red", "A transaction is already open. It will be rollbacked."); printf("\n"); } // request rc = finedb_start(cli->finedb); if (rc) { printf_color("red", "Server error."); printf("\n"); return; } printf_decorated("faint", "Transaction started."); printf("\n"); cli->in_transaction = YTRUE; }
/* Test a connection. */ void command_ping(cli_t *cli) { int rc; // request rc = finedb_ping(cli->finedb); if (rc) { printf_color("red", "Server error."); printf("\n"); return; } printf_decorated("faint", "OK"); printf("\n"); }
/* Stop a transaction. */ void command_stop(cli_t *cli) { int rc; // check connection if needed if (!check_connection(cli)) return; // check opened transaction if (!cli->in_transaction) { printf_color("red", "No opened transaction."); printf("\n"); return; } // request rc = finedb_stop(cli->finedb); if (rc) { printf_color("red", "Server error."); printf("\n"); return; } printf_decorated("faint", "Transaction stopped."); printf("\n"); cli->in_transaction = YFALSE; }
// Инициализация планировщика // Для создания первой задачи, head.S выделяет страницу для структуры // TaskStruct и заполняет ее (используется то, что поле tss является // первым, а tsss - вторым). Адрес страницы заносится в Task[0] еще // до вызова этой функции. void init_scheduler() { printf_color(0x0b, "Starting scheduler...\t\t"FLGREEN"%dHz switching frequency\n", CFG_SCHED_HZ); // Устанавливаем задержку PIT-таймера outb(36, 0x43); outb(TIMER_VALUE & 0xff, 0x40); outb(TIMER_VALUE >> 8, 0x40); // Все остальное для первой задачи уже сделано // Task[0]->pid = 0; // CurPID = 1; CurPID = 0; Current = 0; // NTasks = 1; NTasks = 0; }
// Функция убивает процесс, заданный идентификатором // При этом освобождаются все занятые им страницы, в т.ч. страницы, // содержащие его каталог страниц и TSS void scheduler_kill(ulong pid) { ulong i; for (i = 0; i < NTasks; i++) { if (Task[i]->pid == pid) { uint pagecount = 0; TaskStruct* task = Task[i]; int j, k; // Проходим по каталогу страниц задачи и ищем непустые записи // Для каждой записи проходим по соответствующей таблице страниц // и освобождаем выделенные страницы. По пути считаем их количество. ulong *pg_dir = (ulong*)PAGE_ADDR(task->tss.cr3); for (j = 0; j < 512; j++) if ((ulong)pg_dir[j] & 0x1) { for (k = 0; k < 1024; k++) { addr_t page = ((ulong*)PAGE_ADDR(pg_dir[j]))[k]; if ((page & PA_P) && ((page & PA_NONFREE) == 0)) { pagecount++; free_page(page); } } pagecount++; free_page(pg_dir[j]); } pagecount+=2; free_page(task->tss.cr3); free_page((ulong)task); printf_color(0x4, "\n%d pages freed\n", pagecount); if (NTasks <= 1) // Система осталась без процессов :( return panic("Heh... Last process has died...\n"); Task[i] = Task[NTasks-1]; NTasks--; if (Current >= NTasks) Current = 0; // Вызываем смену задачи, на случай, если убили текущий процесс CALL_SCHEDULER; // Над этим надо еще подумать return; } } }
/* Fetch a value from its key. */ void command_get(cli_t *cli, char *pt) { char *pt2, *key; ybin_t bkey, bdata; int rc; LTRIM(pt); if (*pt != '"') { printf_decorated("faint", "Bad key format (no quote)"); printf("\n"); return; } pt++; if (!*pt) { printf_decorated("faint", "Bad key"); printf("\n"); return; } key = pt2 = pt; pt2 = pt; if ((pt2 = strchr(pt2, '"')) == NULL) { printf_decorated("faint", "Bad key format (no trailing quote)"); printf("\n"); return; } *pt2 = '\0'; // check connection if needed if (!check_connection(cli)) return; // request bzero(&bdata, sizeof(bdata)); ybin_set(&bkey, key, strlen(key)); rc = finedb_get(cli->finedb, bkey, &bdata); if (rc) { printf_color("red", "Unable to get key '%s' (%d).", key, rc); printf("\n"); return; } if (bdata.data == NULL || bdata.len == 0) { printf_decorated("faint", "No data."); printf("\n"); } printf("%s\n", (char*)bdata.data); }
/** * @function check_connection * Check the connection to the server. * @param cli Pointer to the client structure. * @return 1 if OK, 0 if no connection. */ int check_connection(cli_t *cli) { if (!cli->autocheck) return (1); // ping the server if (!finedb_ping(cli->finedb)) return (1); // no connection, try to reconnect if (finedb_connect(cli->finedb) != FINEDB_OK) { printf_color("red", "Lost connection to server."); printf("\n"); return (0); } if (cli->in_transaction) { cli->in_transaction = YFALSE; printf_decorated("faint", "Reconnected to server. Transaction is lost."); } else printf_decorated("faint", "Reconnected to server."); printf("\n"); return (1); }
/* Delete a key. */ void command_del(cli_t *cli, char *pt) { char *pt2, *key; ybin_t bkey; int rc; LTRIM(pt); if (*pt != '"') { printf_decorated("faint", "Bad key format (no quote)"); printf("\n"); return; } pt++; if (!*pt) { printf_decorated("faint", "Bad key"); printf("\n"); return; } key = pt2 = pt; pt2 = pt; if ((pt2 = strchr(pt2, '"')) == NULL) { printf_decorated("faint", "Bad key format (no trailing quote)"); printf("\n"); return; } *pt2 = '\0'; // check connection if needed if (!check_connection(cli)) return; // request ybin_set(&bkey, key, strlen(key)); rc = finedb_del(cli->finedb, bkey); if (rc) printf_color("red", "Unable to delete key '%s'.", key); printf("\n"); printf_decorated("faint", "OK"); printf("\n"); }
void printf_reset_color() { printf_color(-1); }
/* Program the board ID fuses if not already done */ test_return_t program_board_id(void) { const char* const indent = menu_get_indent(); char chip_str[64]; char chip_str_full[64]; char chip_rev_str[64]; char board_str[64]; char board_rev_str[64]; fsl_board_id_t board_id = get_board_id(); chip_name(chip_str, board_id.B.CHIP_TYPE_ID, false); chip_name(chip_str_full, board_id.B.CHIP_TYPE_ID, true); chip_revision(chip_rev_str, board_id.B.CHIP_REV_MAJOR, board_id.B.CHIP_REV_MINOR); board_name(board_str, board_id.B.BOARD_TYPE_ID); board_revision(board_rev_str, board_id.B.BOARD_REV); uint32_t fw_board_type = BOARD_TYPE; uint32_t fw_board_rev = BOARD_REVISION; /* Special case for MX6SDL/DQ SMART_DEVICE/SABRE_AI REV_B boards. * Allow user to choose to program the board as a REV_C or a REV_BX board */ if ((CHIP_TYPE == CHIP_TYPE_MX6SDL || CHIP_TYPE == CHIP_TYPE_MX6DQ) && (BOARD_TYPE == BOARD_TYPE_SABRE_AI || BOARD_TYPE == BOARD_TYPE_SMART_DEVICE) && BOARD_REVISION == BOARD_REVISION_B) { printf("%sThis binary will work for REV_D, REV_C, REV_BX, and REV_B boards.\n", indent); printf("%sWould you like to use the REV_D board ID for this board?\n", indent); if (is_input_char('y', indent)) { printf("%sUsing REV_D board ID instead of REV_B board ID.\n\n", indent); fw_board_rev = BOARD_REVISION_D; } else { printf("%sWould you like to use the REV_C board ID for this board?\n", indent); if (is_input_char('y', indent)) { printf("%sUsing REV_C board ID instead of REV_B board ID.\n\n", indent); fw_board_rev = BOARD_REVISION_C; } else if(BOARD_TYPE == BOARD_TYPE_SABRE_AI){ printf("%sWould you like to use the REV_BX board ID for this board?\n", indent); if (is_input_char('y', indent)) { printf("%sUsing REV_BX board ID instead of REV_B board ID.\n\n", indent); fw_board_rev = BOARD_REVISION_BX; } } } } /* Special case for MX6SL EVB/EVK boards. * Allow user to choose to program the board as a EVK_EPDC or EVK_SPDC board */ if (CHIP_TYPE == CHIP_TYPE_MX6SL) { printf("%sThis binary will work for both EVB and EVK boards.\n", indent); printf("%sWould you like to use the EVK board ID for this board?\n", indent); if (is_input_char('y', indent)) { printf("%sUsing BOARD_TYPE_EVK board ID instead of BOARD_TYPE_EVB board ID.\n\n", indent); printf("%sUsing BOARD_REVISION_A board ID instead of BOARD_REVISION_B board ID.\n\n", indent); fw_board_type = BOARD_TYPE_EVK; fw_board_rev = BOARD_REVISION_A; } } if (board_id.B.BOARD_TYPE_ID == 0 || board_id.B.BOARD_REV == 0) { // Board is not programmed printf("%sNo Board ID found in the fuses.\n", indent); board_id.B.BOARD_TYPE_ID = fw_board_type; board_id.B.BOARD_REV = fw_board_rev; printf("%sThis OBDS binary will program Board ID to 0x%08X as detailed below:\n", indent, board_id.U); show_board_id(board_id, indent); printf_color(g_TextAttributeBold, g_TextColorRed, "%sContinue with irreversible operation to program Board ID?\n", indent); if (!is_input_char('y', indent)) { /* Do not program the suggested value to Board ID fuse bank */ printf("%sNOT programming board ID to fuses.\n", indent); return TEST_BYPASSED; } // DO THE PROGRAMMING test_return_t err = program_board_id_fuses(board_id.B.BOARD_TYPE_ID, board_id.B.BOARD_REV, indent); if (err == TEST_PASSED) { printf("%sFuses programmed successfully.\n\n", indent); show_board_id(get_board_id(), indent); } return err; } else if ((board_id.B.BOARD_TYPE_ID == BOARD_TYPE_SABRE_AI || board_id.B.BOARD_REV == BOARD_REVISION_B) && (fw_board_rev == BOARD_REVISION_BX) ) { // SABRE AI Board is programmed as REV_B , but we need it to be REV_BX printf("\n%sSABRE AI Rev. B board ID found in the fuses.\n", indent); board_id.B.BOARD_TYPE_ID = fw_board_type; board_id.B.BOARD_REV = fw_board_rev; printf("%sThis OBDS binary will program Board ID to 0x%08X as detailed below:\n", indent, board_id.U); show_board_id(board_id, indent); printf("\n"); printf_color(g_TextAttributeBold, g_TextColorRed, "%sContinue with irreversible operation to program Board ID?\n", indent); if (!is_input_char('y', indent)) { /* Do not program the suggested value to Board ID fuse bank */ printf("%sNOT programming board ID to fuses.\n", indent); return TEST_BYPASSED; } // DO THE PROGRAMMING test_return_t err = program_board_id_fuses(board_id.B.BOARD_TYPE_ID, board_id.B.BOARD_REV, indent); if (err == TEST_PASSED) { printf("%sFuses programmed successfully.\n\n", indent); show_board_id(get_board_id(), indent); } return err; } else if ( board_id.B.CHIP_TYPE_ID != CHIP_TYPE || board_id.B.BOARD_TYPE_ID != fw_board_type || board_id.B.BOARD_REV != fw_board_rev ) { // Software is not compiled for this board printf("\n%sSoftware is not compiled for this board.\n", indent); chip_name(chip_str, CHIP_TYPE, false); board_name(board_str, fw_board_type); board_revision(board_rev_str, fw_board_rev); printf("%sSoftware for %s %s %s.\n", indent, chip_str, board_str, board_rev_str); chip_name(chip_str, board_id.B.CHIP_TYPE_ID, false); board_name(board_str, board_id.B.BOARD_TYPE_ID); board_revision(board_rev_str, board_id.B.BOARD_REV); printf("%sBoard is %s %s %s.\n", indent, chip_str, board_str, board_rev_str); return TEST_FAILED; } else if ( board_id.B.CHIP_TYPE_ID == CHIP_TYPE && board_id.B.BOARD_TYPE_ID == fw_board_type && board_id.B.BOARD_REV == fw_board_rev ) { // Board ID fuses are already correct printf("\n%sBoard ID fuses are already programmed.\n\n", indent); show_board_id(board_id, indent); return TEST_PASSED; } else { // Unhandled cases printf("\n%sUnknown failure.\n\n", indent); show_board_id(board_id, indent); return TEST_FAILED; } }
/* Put, add or update a key/value in database. */ void command_send_data(cli_t *cli, char *pt, ybool_t create_only, ybool_t update_only) { char *pt2, *key, *data; ybin_t bkey, bdata; int rc; LTRIM(pt); if (*pt != '"') { printf_decorated("faint", "Bad key format (no quote)"); printf("\n"); return; } pt++; if (!*pt) { printf_decorated("faint", "Bad key"); printf("\n"); return; } key = pt2 = pt; pt2 = pt; if ((pt2 = strchr(pt2, '"')) == NULL) { printf_decorated("faint", "Bad key format (no trailing quote)"); printf("\n"); return; } *pt2 = '\0'; pt2++; if (!*pt2) { printf_decorated("faint", "Missing data"); printf("\n"); return; } *pt2 = '\0'; data = pt2 + 1; LTRIM(data); if (*data != '"') { printf_decorated("faint", "Bad data format (no quote)"); printf("\n"); return; } data++; if (!*data) { printf_decorated("faint", "Missing data"); printf("\n"); return; } pt2 = data + strlen(data) - 1; if (*pt2 != '"') { printf_decorated("faint", "Bad data format (no trailing quote)"); printf("\n"); return; } *pt2 = '\0'; // check connection if needed if (!check_connection(cli)) return; // request ybin_set(&bkey, key, strlen(key)); ybin_set(&bdata, data, strlen(data)); if (create_only) rc = finedb_add(cli->finedb, bkey, bdata); else if (update_only) rc = finedb_update(cli->finedb, bkey, bdata); else rc = finedb_put(cli->finedb, bkey, bdata); if (rc) printf_color("red", "Unable to %s key '%s'.", (create_only ? "add" : (update_only ? "update" : "put")), key); else printf_decorated("faint", "OK"); printf("\n"); }
// Инициализация PIC void irq_init() { puts_color("Remapping IRQs...\t\t", 0x0b); remap_irqs(IRQ0_INT, IRQ8_INT); printf_color(0x0a, "IRQ0 = int 0x%x, IRQ8 = int 0x%x\n", IRQ0_INT, IRQ8_INT); }
int main(void) { int pid, wpid, fd2; if(open("/dev/console", O_RDWR) < 0) { mknod("/dev/console", 1, 1); } open("/dev/console", O_RDWR); dup(0); // stdout dup(0); // stderr mknod("/dev/eth0", 2, 2); if((fd2 = open("/dev/eth0", O_RDONLY)) < 0) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "init: "); printf_color(COLOR_BLACK, COLOR_RED, true, 2, "Error opening /dev/eth0\n"); exit(); return 1; } else { u8int buf[512]; int n; net_interface_t *nic; if((n = read(fd2, buf, sizeof(buf))) > 0 && n > 0) { nic = malloc(n); memmove(nic, buf + 4, n); if(nic->init_success) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 1, "init:"); printf(1, " starting ethernet RX daemon\n"); pid = fork(); if(pid < 0) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "init: "); printf_color(COLOR_BLACK, COLOR_RED, true, 2, "fork failed\n"); exit(); } if(pid == 0) { exec("/sbin/ethrx_daemon", argveth); printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "init: "); printf_color(COLOR_BLACK, COLOR_RED, true, 2, "exec ethrx_daemon failed\n"); exit(); } } } } for(;;) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 1, "init:"); printf(1, " starting sh\n"); pid = fork(); if(pid < 0) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "init: "); printf_color(COLOR_BLACK, COLOR_RED, true, 2, "fork failed\n"); exit(); } if(pid == 0) { exec("/bin/sh", argvsh); printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "init: "); printf_color(COLOR_BLACK, COLOR_RED, true, 2, "exec sh failed\n"); exit(); } while((wpid = wait()) >= 0 && wpid != pid) //printf_color(COLOR_BLACK, COLOR_GREEN, true, 1, "zombie: wpid %d pid %d\n", wpid, pid); { kill(wpid); } } }
int main() { bool fl_end = false, // индикатор конца игры fl_hod_gamer = false, // индикатор хода игрока fl_hod_comp = false, // индикатор хода компа fl_err = false; // индикатор ошибки int a=0,b=0/*,end*/, // просто переменные Npos=-1, // номер известной позиции win=0, // победитель count=1, // счётчик ходов gamerX=-1, // столбик игрока gamerY=-1, // строка игрока compX=-1, // столбик компа compY=-1; // строка компа sys_clear_screen(); printf_color(0x0d, "X-O by Denis Zgursky, 2005\nHelloOS port by Ilya Skriblovsky\n\n"); printf_color(0x0d, "Controls:\n W\nA S D Enter\n\n"); while(fl_end==false && count<=5) { // выводим сетку draw_field(); // int i; // for( i=0;i<8;i++) // { // int j; // for( j=0;j<8;j++) // printf("%c",setka[i][j]); // printf("\n"); // } // "обнуляем" переменные fl_hod_gamer=false; fl_hod_comp=false; gamerX=-1; gamerY=-1; compX=-1; compY=-1; // ход игрока: заполняем Field и setka while(fl_hod_gamer==false) { while (1) { char k = sys_getch(); if (k == 0x0d) { gamerY = cury; gamerX = curx; break; } switch (k) { case 'w': if (cury > 0) cury--; break; case 's': if (cury < 2) cury++; break; case 'a': if (curx > 0) curx--; break; case 'd': if (curx < 2) curx++; break; } draw_field(); } if(Field[gamerY][gamerX]==0) { Field[gamerY][gamerX]=2; switch(gamerY) { case 0: b=gamerY+2; break; case 1: b=gamerY+3; break; case 2: b=gamerY+4; break; } switch(gamerX) { case 0: a=gamerX+2; break; case 1: a=gamerX+3; break; case 2: a=gamerX+4; break; } setka[b][a]='X'; fl_hod_gamer=true; } // } } // если пятый ход, то проверяем на возможность победы и заканчиваем if(count==5) { fl_end=true; fl_hod_comp=true; win=Victory(Field); } // анализ первого хода if(count==1) { if((gamerY==0 && gamerX==0) || (gamerY==0 && gamerX==2) || (gamerY==2 && gamerX==0) || (gamerY==2 && gamerX==2)) { compY=1; compX=1; } if((gamerY==0 && gamerX==1) || (gamerY==2 && gamerX==1)) { compY=gamerY; compX=gamerX-1; } if((gamerY==1 && gamerX==0) || (gamerY==1 && gamerX==2)) { compY=gamerY+1; compX=gamerX; } if(gamerY==1 && gamerX==1) { compY=0; compX=2; } fl_hod_comp=true; } // проверка на выигрыш/проигрыш if(fl_hod_comp==false) { win=Victory(Field); if(win==1 || win==2) { fl_hod_comp=true; fl_end=true; } } // проверка на возможность выигрыша if(fl_hod_comp==false) { opr(Field,1,&compY,&compX); if(compY!=-1 && compX!=-1) fl_hod_comp=true; } // прверка на возможность проигрыша if(fl_hod_comp==false) { opr(Field,2,&compY,&compX); if(compY!=-1 && compX!=-1) fl_hod_comp=true; } // прверка на схожесть с известной позицией if(fl_hod_comp==false) { Npos=pos(Field); if(Npos!=-1) { prod(Npos,&compY,&compX); fl_hod_comp=true; } } // просто ход if(fl_hod_comp==false) { hod(Field,&compY,&compX); fl_hod_comp=true; } // заносим запись в Field и в setka, иначе ошибка if(fl_hod_comp==true && fl_end==false && compY!=-1 && compX!=-1) { Field[compY][compX]=1; switch(compY) { case 0: b=compY+2; break; case 1: b=compY+3; break; case 2: b=compY+4; break; } switch(compX) { case 0: a=compX+2; break; case 1: a=compX+3; break; case 2: a=compX+4; break; } setka[b][a]='O'; } else { if(fl_end==false) { fl_err=true; fl_end=true; } } // проверяем не победил ли комп после своего хода if(fl_err==false && fl_hod_comp==true) { win=Victory(Field); if(win==1 || win==2) fl_end=true; } count++; } // если нет ошибки то выводим результат if(fl_err==false) { int i; for( i=0;i<8;i++) { int j; for( j=0;j<8;j++) printf("%c",setka[i][j]); printf("\n"); } switch(win) { case 0: printf("Drawn game\n"); break; case 1: printf("I win! :)\n"); break; case 2: printf("Your win! :(\n"); break; } } else { printf("Error!Sorry!"); } return 0; }
int main(int argc, char *argv[]) { eth_packet_t *packet; net_interface_t *nic; char *buf = malloc(1600); // max_eth_frame_length + breathing room int n, fd2, pid; if((fd2 = open("/dev/eth0", O_RDONLY)) < 0) { printf_color(COLOR_BLACK, COLOR_RED, true, 2, "Error opening /dev/eth0\n"); free(buf); exit(); return 1; } else { if((n = read(fd2, buf, sizeof(buf))) > 0 && n > 0) { nic = malloc(n); memmove(nic, buf, n); if(! nic->init_success) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "ethrx: "); printf(2, "no network interface initialized\n\n"); free(buf); exit(); return 2; } } else { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "ethrx: "); printf(2, "no cards found\n"); free(buf); exit(); return 2; } } // kernel driver to ethrx IPC int mypid = getpid(); int arpdirecnum, direcnum; if((direcnum = claim_direct_ipc_r("ethrxd", mypid)) < 0) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "ethrx: "); printf_color(COLOR_BLACK, COLOR_RED, true, 2, "\ncould not reserve ipc direct!\n"); free(buf); exit(); return 1; } // spawn ARP daemon char *argvarp[] = { "arp_daemon", argv[1], 0 }; printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 1, "ethrx:"); printf(1, " starting ARP daemon\n"); pid = fork(); if(pid < 0) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "ethrx: "); printf_color(COLOR_BLACK, COLOR_RED, true, 2, "fork failed\n"); exit(); } if(pid == 0) { exec("/sbin/arp_daemon", argvarp); printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "ethrx: "); printf_color(COLOR_BLACK, COLOR_RED, true, 2, "exec arp_daemon failed\n"); exit(); } // ethrx to ARP IPC direct_ipc_new("arp"); if((arpdirecnum = claim_direct_ipc_w("arp", mypid)) < 0) { printf_color(COLOR_BLACK, COLOR_LIGHT_BLUE, true, 2, "ethrx: "); printf_color(COLOR_BLACK, COLOR_RED, true, 2, "\ncould not claim arp IPC write\n"); free(buf); exit(); return 1; } // start accepting RX if(nic->driver_id == drv_rtl8139) { uoutw(nic->ioaddr + rtl_interrupt_mask, rtl_interrupts_OK); } // ready the buffer packet packet = malloc(sizeof(rx_packet_t) + 1600); for(;;) { if( (n = direct_ipc_get_src_leng(direcnum)) > 0 && n > 0) { if(direct_ipc_read("ethrxd", direcnum, mypid, buf, n) <= 0) { continue; } // handle packet memset(&packet->data[0], 0, 1514); memmove(packet, buf, n); dbg_printf(1, "\nReceived length %d bytes", n); dbg_printf(1, "\nDesination MAC: %x:%x:%x:%x:%x:%x", packet->dest[0], packet->dest[1], packet->dest[2], packet->dest[3], packet->dest[4], packet->dest[5]); dbg_printf(1, "\nSource MAC: %x:%x:%x:%x:%x:%x", packet->src[0], packet->src[1], packet->src[2], packet->src[3], packet->src[4], packet->src[5]); switch(b_l_w(packet->type)) { // b_l_w is convert a word from big to little endian case eth_frame_type_arp: dbg_printf(1, "\nType: ARP\n"); direct_ipc_write("arp", arpdirecnum, mypid, (unsigned char*) &packet->data[0], arp_packet_size); break; case eth_frame_type_ipv4: dbg_printf(1, "\nType: IPv4\n"); break; case eth_frame_type_ipv6: dbg_printf(1, "\nType: IPv6\n"); break; case eth_frame_type_ipx: dbg_printf(1, "\nType: IPX\n"); break; case eth_frame_type_aptk: dbg_printf(1, "\nType: AppleTalk\n"); break; case eth_frame_type_aarp: dbg_printf(1, "\nType: AARP\n"); break; case eth_frame_type_wol: dbg_printf(1, "\nType: Wake-On-LAN\n"); break; case eth_frame_type_eap: dbg_printf(1, "\nType: 802.1X\n"); break; case eth_frame_type_xp: dbg_printf(1, "\nType: XP\n"); break; default: dbg_printf(1, "\nType: Unknown, %x\n", b_l_w(packet->type)); break; } } //*******// //sleep()// //*******// } free(buf); free(packet); exit(); return 2; }
/* Main function. */ int main(int argc, char *argv[]) { cli_t cli; char *hostname = DEFAULT_HOST; char history_file[4096]; ybool_t interactive_mode = YTRUE; bzero(&cli, sizeof(cli_t)); cli.autocheck = YTRUE; if (argc == 2 && argv[1][0] != '-') hostname = argv[1]; if (argc == 3 && !strcmp(argv[2], "-")) interactive_mode = YFALSE; // init database connection if ((cli.finedb = finedb_create(hostname, 11138)) == NULL) { printf_color("red", "Memory error."); printf("\n"); exit(1); } if (finedb_connect(cli.finedb) != FINEDB_OK) { printf_color("red", "Unable to connect to server '%s' on port '%d'.", argv[1], 11138); printf("\n"); exit(2); } // interactive mode init if (interactive_mode) { char *home = NULL; if ((home = getenv("HOME")) != NULL) { FILE *hist; snprintf(history_file, sizeof(history_file), "%s/%s", home, HISTORY_FILE); if ((hist = fopen(history_file, "w+")) != NULL) { fclose(hist); linenoiseHistoryLoad(HISTORY_FILE); } linenoiseSetCompletionCallback(cli_completion); } } // main loop for (; ; ) { char buff[4096], *line = NULL, *pt, *cmd; if (!interactive_mode) { ssize_t bufsz, linesz = 0; while ((bufsz = read(0, buff, sizeof(buff))) > 0) { pt = (char*)malloc(linesz + bufsz + 1); memcpy(pt, line, linesz); memcpy((void*)((size_t)pt + linesz), buff, bufsz); linesz += bufsz; pt[linesz] = '\0'; if (line) free(line); line = pt; } } else { snprintf(buff, sizeof(buff), "%s > ", (cli.dbname ? cli.dbname : "default")); if ((line = linenoise(buff)) == NULL) break; } pt = line; LTRIM(pt); cmd = pt; // add command line to history linenoiseHistoryAdd(cmd); linenoiseHistorySave(history_file); // extract the command while (*pt && !IS_SPACE(*pt)) ++pt; *pt++ = '\0'; LTRIM(pt); /* command management */ if (cmd[0] == '\0') goto reloop; //continue; // local commands, no need for a running connection if (!strcasecmp(cmd, "exit") || !strcasecmp(cmd, "quit")) exit(0); if (!strcasecmp(cmd, "help") || cmd[0] == '?') { command_help(); goto reloop; //continue; } else if (!strcasecmp(cmd, "sync")) { command_sync(&cli); goto reloop; //continue; } else if (!strcasecmp(cmd, "async")) { command_async(&cli); goto reloop; //continue; } // commands that need a running connection if (!strcasecmp(cmd, "use")) command_use(&cli, pt); else if (!strcasecmp(cmd, "get")) command_get(&cli, pt); else if (!strcasecmp(cmd, "del")) command_del(&cli, pt); else if (!strcasecmp(cmd, "put")) command_send_data(&cli, pt, YFALSE, YFALSE); else if (!strcasecmp(cmd, "add")) command_send_data(&cli, pt, YTRUE, YFALSE); else if (!strcasecmp(cmd, "update")) command_send_data(&cli, pt, YFALSE, YTRUE); else if (!strcasecmp(cmd, "inc")) command_inc(&cli, pt); else if (!strcasecmp(cmd, "dec")) command_dec(&cli, pt); else if (!strcasecmp(cmd, "start")) command_start(&cli); else if (!strcasecmp(cmd, "stop")) command_stop(&cli); #if 0 else if (!strcasecmp(cmd, "list")) command_list(&cli, pt); #endif else if (!strcasecmp(cmd, "ping")) command_ping(&cli); else if (!strcasecmp(cmd, "autocheck")) command_autocheck(&cli, pt); else { printf_color("red", "Bad command."); printf("\n"); } reloop: free(line); } return (0); }
void print_number(int n) { printf_color(n); printf("%d", n); printf_reset_color(); }