int message_complete_cb(http_parser* parser) { struct request_info *r = parser->data; struct stat file_stat; int exists; char datestring[256]; struct tm *tm; if (strstr(r->file, "..") != NULL) { send_error(r, 404); return 0; } exists = stat(r->file, &file_stat); if (exists != 0){ switch (errno){ case EACCES: send_error(r, 403); break; default: send_error(r, 404); break; } return 0; } else { /* The file exists */ /* Test if it's a folder */ if (S_ISDIR(file_stat.st_mode) > 0) { send_error(r, 404); return 0; } tm = localtime(&file_stat.st_mtime); /* Get localized date string. */ strftime(datestring, sizeof(datestring), DATE_FORMAT, tm); evbuffer_add_printf(r->buf, "HTTP/1.0 200 OK\r\n"); evbuffer_add_printf(r->buf, "Content-Length: %9jd\r\n", (intmax_t)file_stat.st_size); evbuffer_add_printf(r->buf, "Last-Modified: %s\r\n", datestring); add_headers(r->buf); } if (parser->method == HTTP_HEAD) { event_add(&r->wr_ev, NULL); } else { // Open the file for parsing to body if (read_from_file(r) == -1) { evbuffer_drain(r->buf, EVBUFFER_LENGTH(r->buf)); send_error(r, 500); return 0; } // Send reponse with body now :) event_add(&r->wr_ev, NULL); } printf("complete\n"); return 0; }
static void read_cpu_scaling_governor(void) { nominal_cpu_scaling_governor = read_from_file(config_file.cpufreq_file_paths[SCALING_GOVERNOR_PATH]); /* * FIXME : Should be fully useless. But without this, the * value of nominal_cpu_scaling_governor is not correct when used */ if (strcmp(nominal_cpu_scaling_governor, ("hotplug")) == 0) nominal_cpu_scaling_governor = "hotplug"; else if (strcmp(nominal_cpu_scaling_governor, ("conservative")) == 0) nominal_cpu_scaling_governor = "conservative"; else if (strcmp(nominal_cpu_scaling_governor, ("ondemand")) == 0) nominal_cpu_scaling_governor = "ondemand"; else if (strcmp(nominal_cpu_scaling_governor, ("userspace")) == 0) nominal_cpu_scaling_governor = "userspace"; else if (strcmp(nominal_cpu_scaling_governor, ("performance")) == 0) nominal_cpu_scaling_governor = "performance"; #ifdef DEBUG LOGD("nominal_cpu_scaling_governor is %s\n", nominal_cpu_scaling_governor); fflush(stdout); #endif }
/** * Run the process **/ process_return_t* pm_run_process(process_t *process) { process_return_t* ret = pm_new_process_return(); // Setup the stdin int child_stdin; if (ret == NULL) return NULL; if (process->env) process->env[process->env_c] = NULL; // Run afterhook if (process->before) { if (run_hook(BEFORE_HOOK, process, ret)) return ret; } ret->stage = PRS_COMMAND; pid_t pid = pm_execute(1, (const char*)process->command, (const char*)process->cd, (int)process->nice, (const char**)process->env, &child_stdin, (const char*)process->stdout, (const char*)process->stderr); ret->pid = pid; ret->exit_status = wait_for_pid(pid, 0); if (ret->exit_status) { if (errno) { if (process->stdout) ret->stdout = read_from_file((const char*)process->stdout); if (process->stderr) ret->stderr = read_from_file((const char*)process->stderr); else { ret->stderr = (char*)calloc(1, sizeof(char)*strlen(strerror(errno))); strncpy(ret->stderr, strerror(errno), strlen(strerror(errno))); } } return ret; } // Run afterhook if (process->after) { if (run_hook(AFTER_HOOK, process, ret)) return ret; } // Yay, we finished properly ret->stage = PRS_OKAY; return ret; }
bool read_from_file_optional( const std::string &path, const std::function<void( std::istream & )> &reader ) { // Note: slight race condition here, but we'll ignore it. Worst case: the file // exists and got removed before reading it -> reading fails with a message // Or file does not exists, than everything works fine because it's optional anyway. return file_exist( path ) && read_from_file( path, reader ); }
/* * Initialize some internal parameters. */ void init_cpu_thermal_governor(u32 omap_temp) { int i; /* Initialize the nominal_cpu_scaling_max_freq variable */ current_scaling_max_freq = atoi(read_from_file( config_file.cpufreq_file_paths[SCALING_MAX_FREQ_PATH])); /* Initialize the nominal_cpu_scaling_governor variable */ read_cpu_scaling_governor(); /* Initialize the available_freq[] int array */ read_cpu_scaling_available_freq(); /* Initialize the nominal maximum CPU frequency from the available_freq array */ nominal_cpu_scaling_max_freq = available_freq[0]; for (i = 1; i < OPPS_NUMBER; i++) { if (available_freq[i] > nominal_cpu_scaling_max_freq) nominal_cpu_scaling_max_freq = available_freq[i]; } #ifdef DEBUG LOGD("nominal/current_scaling_max_freq is %ld / %ld\n", nominal_cpu_scaling_max_freq, current_scaling_max_freq); #endif /* Initialize the available_governors[] string array */ read_cpu_scaling_available_governors(); /* Check if "conservative" governor is available */ for (i = 0; i < GOVS_NUMBER; i++) { if (strcmp(available_governors[i],("conservative")) == 0) { is_conservative_available = true; } } #ifdef DEBUG if (is_conservative_available == true) { LOGD("conservative governor is available\n"); fflush(stdout); } else { LOGD("conservative governor is not available\n"); fflush(stdout); } #endif /* * Force to initialize all temperature thresholds according to * the current thermal zone */ cpu_thermal_governor(omap_temp); #ifdef DEBUG for (i = 0; i < OPPS_NUMBER; i++) { LOGD("available_freq[%d] = %ld\n", i, available_freq[i]); fflush(stdout); } #endif }
int get_config_value(char *config_key, char *reference) { char config_path[60]; strcpy(config_path, CONFIG_ROOT); strcat(config_path, config_key); return read_from_file(config_path, 30, reference); }
Peer::Peer(const string &configFile) { config = new Configuration(configFile); set_id(get_host_id(config->hostIdType)); schedulerVec = read_from_file(config->schedulerMemFile); set_index(get_self_idx(get_id(), schedulerVec)); running = true; numZHTMsg = 0; init_zht_client(config->zhtConfigFile, config->zhtMemFile); }
bool session_file_storage::load(std::string const &sid,time_t &timeout,std::string &out) { locked_file file(this,sid); if(!read_from_file(file.handle(),timeout,out)) { ::DeleteFile(file.name().c_str()); return false; } return true; }
void android_main(android_app* state) { app_dummy(); LOGW("entered main"); state->userData = NULL; state->onAppCmd = engine_handle_cmd; state->onInputEvent = engine_handle_input; // sdcard example std::string file("/sdcard/text.txt"); LOGW("test file : %s", file.c_str()); write_to_file(file, "simple text"); read_from_file(file); // device memory example /// @todo : fix error file = std::string("std_text.txt"); LOGW("test file : %s", file.c_str()); write_to_file(file, "simple text"); read_from_file(file); while (true) { int ident; int events; android_poll_source* source; while ((ident = ALooper_pollAll(-1, NULL, &events, (void**) &source)) >= 0) { if (source != NULL) { source->process(state, source); } if (state->destroyRequested != 0) { LOGW("exited main"); return; } } } }
void __fastcall TForm1::Button2Click(TObject *Sender) { start=1; //ответ не выбран Panel1->BevelInner=bvNone; Panel2->BevelInner=bvNone; if (answer==-1) { Application->MessageBox("Выберите вариант ответа","Ошибка",MB_OK); return; } if (answer==1) { Show_rate(Form1); return; } if (answer==0) { answer=-1; current_q++; String q=read_from_file(rates[current_rate],current_q); if (q!="")//если есть ещё вопросы в этом возрасте Memo1->Text=q; //вывод вопроса else { if (current_rate!=num_of_rates-1) { current_rate++;//в следующую возраст. группу current_q=1; //с первого вопроса String q=read_from_file(rates[current_rate],current_q); //дошли до 0+ if (current_rate==4) Show_rate(Form1); else Memo1->Text=q; } else Show_rate(Form1); } } start=0; }
int main(int argc, char *argv[]) { if (argc < 4) { fprintf(stderr, "Usage %s infile outfile threads\n", argv[0]); exit(-1); } int fd_in = open(argv[1], O_RDONLY); int fd_out = open(argv[2], O_RDWR | O_CREAT | O_TRUNC, S_IRWXU); unsigned long uncomp_array_size = atol(argv[3]); lz4_uncompression_work *uncomp_array; pthread_t lz4uncomp_thread[uncomp_array_size]; unsigned long uncomp_ptr; unsigned long total_bytes = 0; uncomp_array = new lz4_uncompression_work[uncomp_array_size]; for (unsigned long i = 0; i < uncomp_array_size; i++) { uncomp_array[i].fd_in = fd_in; if(pthread_create(&lz4uncomp_thread[i], NULL, lz4_uncomp_service_start, &uncomp_array[i]) != 0) { printf("failed to launch exec thread\n"); exit(-1); } } unsigned long nextbytes; unsigned char header[11]; read_from_file(fd_in, header, 11); nextbytes = uncomp_array[0].startup(header); for (unsigned long i = 1; i < uncomp_array_size; i++) { (void) uncomp_array[i].startup(header); } for (unsigned long i = 0; i < uncomp_array_size; i++) { total_bytes += nextbytes; nextbytes = uncomp_array[i].fill(nextbytes); uncomp_array[i].busy = true; } uncomp_ptr = 0; while (uncomp_array[uncomp_ptr].fillbytes) { while (uncomp_array[uncomp_ptr].busy); /* Write Block */ flush_output(fd_out, (char *) uncomp_array[uncomp_ptr].uncomp_data, uncomp_array[uncomp_ptr].uncomp_bytes); total_bytes += nextbytes; nextbytes = uncomp_array[uncomp_ptr].fill(nextbytes); uncomp_array[uncomp_ptr].busy = true; uncomp_ptr = (uncomp_ptr + 1) % uncomp_array_size; } for (unsigned long i = 0; i < uncomp_array_size; i++) { uncomp_array[i].shutdown(); uncomp_array[i].terminate = true; pthread_join(lz4uncomp_thread[i], NULL); } printf("Decompressed %lu\n", total_bytes); return 0; }
int main(int argc, char **argv) { FILE *in = argc > 1 ? fopen(argv[1], "r") : NULL; int n = argc > 2 ? atoi(argv[2]) : 20; int step = argc > 3 ? atoi(argv[3]) : 1; int i; char *base = argc > 4 ? argv[4] : "output/life"; char filename[255]; char *filenametemp = base; strcpy(filename, filenametemp); //int basenamel = strlen(filename); #ifdef DEBUG //printf("basenamel = %d\n", basenamel); #endif char basename[255]; strcpy(basename, filename); if(in == NULL) { if(argc > 1) fprintf(stderr, "%s: problem z otwarciem pliku %s.\n", argv[0], argv[1]); else fprintf(stderr, "%s: prosze podac plik z danymi.\n", argv[0]); return 1; } board_t *b = read_from_file(in); //write_to_file(b, stdout); board_t *backb = prepare_backstage_board(b); for(i = 0; i < n; i++) { if(i % step == 0) { /* tworzenie nazwy pliku */ filename[0] = '\0'; strcat(filename, basename); strcat(filename, "_"); // dopisanie do filename znaku _ char buf[20]; sprintf(buf, "%03d", i); // zamiana i na const char* char* c = buf; strcat(filename, c); // dopisanie do filename numeru generacji strcat(filename, ".bmp"); // dopisanie do filename .bmp write_to_bmp(b, filename); } prepare_next_states(b, backb); // to, co w momencie rozpoczecia tej funkcji jest na backb nas nie obchodzi swap_boards(&b, &backb); } //printf("Stan planszy %d generacji pozniej:\n", n); //write_to_file(b, stdout); return 0; }
void read_from_textfile(char *filename) { FILE *fp = NULL; fp = fopen(filename, "r"); if (fp == NULL) { fprintf(stderr, "Can't open file %s\n", filename); exit(1); } read_from_file(fp); fclose(fp); }
std::pair<configuration_parameters, std::vector<run_result> > read_from_files(const typename run_result::time_t &now, std::size_t count, char ** fnames){ std::pair<configuration_parameters, std::vector<run_result> > result; for (std::size_t i = 0; i < count; ++i){ auto partial = read_from_file(now,fnames[i]); if (i > 0) assert (same_run(result.first,partial.first)); result.first = partial.first; result.second.insert(result.second.end(),partial.second.begin(),partial.second.end()); } return result; }
void read_old_scan(const char *path) { size_t i; int fd; char *buf; struct stat sb; const char *entry_start; const char *l_start, *l_end; const char *s_start, *s_end; const char *line, *eol; for (i = 0; i < HASH_SIZE; ++i) SLIST_INIT(&hash_table[i]); if (path == NULL) return; if ((fd = open(path, O_RDONLY)) == -1) return; if (fstat(fd, &sb) == -1) { close(fd); return; } scan_mtime = sb.st_mtime; buf = read_from_file(fd); entry_start = buf; l_start = l_end = NULL; entry_start = buf; s_start = s_end = NULL; for (line = buf; *line; line = eol) { eol = strchr(line, '\n'); if (eol == NULL) errx(1, "Incomplete old scan"); ++eol; if (strncmp(line, "PKGNAME=", 8) == 0) { if (line == buf) continue; add_entry(l_start, l_end, s_start, s_end, entry_start, line); l_start = l_end = NULL; entry_start = line; s_start = s_end = NULL; } else if (strncmp(line, "PKG_LOCATION=", 13) == 0) { l_start = line + 13; l_end = eol - 1; } else if (strncmp(line, "SCAN_DEPENDS=", 13) == 0) { s_start = line + 13; s_end = eol - 1; } } if (entry_start != line) add_entry(l_start, l_end, s_start, s_end, entry_start, line); }
static void do_restore_tls_stack(int sckpt_fd) { int tnr = ckpt_head.tnr; TRACE(REPLAYER_TARGET, "tnr = %d\n", tnr); replay_init_tls(tnr); stack_base = TNR_TO_STACK(tnr); stack_end = stack_base + TLS_STACK_SIZE; void * real_stack_base = stack_base + GUARDER_LENGTH; while (TRUE) { struct mem_region region; read_from_file(sckpt_fd, ®ion, sizeof(region)); if (region.start == MEM_REGIONS_END_MARK) FATAL(REPLAYER_TARGET, "unable to find tls stack in ckpt\n"); skip_nbytes(sckpt_fd, region.fn_sz); /* read real region sz */ int real_region_sz; read_from_file(sckpt_fd, &real_region_sz, sizeof(real_region_sz)); TRACE(REPLAYER_TARGET, "compare: 0x%8x-0x%8x %8x-%8x\n", region.start, region.end, (uintptr_t)real_stack_base, (uintptr_t)stack_end); if ((region.start == (uintptr_t)real_stack_base) && (region.end == (uintptr_t)stack_end)) { /* we find it! */ read_from_file(sckpt_fd, real_stack_base, TLS_STACK_SIZE - GUARDER_LENGTH); break; } skip_nbytes(sckpt_fd, real_region_sz); } TRACE(REPLAYER_TARGET, "tls stack is restored\n"); }
int search_by_code(char* entidad, int code){ FILE * block_file; struct record_t *record; struct block_t * current_block; struct file_header * file_header; int res, i = 1, j = 1, recs = 0; int current_pos = 0, encontrado = 1; block_file = open_block_file(entidad, 2); if(!block_file){ return BAD_NAME_FILE; } /* Allocate buffer and record */ record = (struct record_t*) malloc(sizeof(struct record_t)); current_block = (struct block_t *) malloc(sizeof(struct block_t)); file_header = (struct file_header*) malloc(sizeof(struct file_header)); if(!record || !current_block || !file_header) return ALLOCATE_FAIL; initialize_record(record); initialize_block(current_block,1); read_header(block_file, file_header); while((i < file_header->total_blocks+1) && (encontrado == 1)){ current_pos = 0; j = 1; res = read_from_file(block_file, current_block, file_header, i); if(res == RES_OK){ recs = current_block->total_reg; while((j < recs+1) && (encontrado == 1)){ initialize_record(record); current_pos += read_block(current_block, record, current_pos); if(code == record->code){ print_success_message(record); encontrado = 0; } free(record->content); j++; } } i++; } if(encontrado == 1){ print_error_message(code); } free(record); free(file_header); free(current_block); fclose(block_file); return res; }
static void windows_tz_to_tzid(char *buf, int max, Str name) { Tok tk; char *path = path_normalize(NULL, fs->fox_home, "data" SEP_S "windows-tz.txt", -1, NULL); char *ini_buf = read_from_file(NULL, path, NULL); free(path); if (buf == NULL) { goto ERROR_END; } Tok_simple_init(&tk, ini_buf); Tok_simple_next(&tk); for (;;) { switch (tk.v.type) { case TL_STR: if (str_eq(tk.str_val.p, tk.str_val.size, name.p, name.size)) { Tok_simple_next(&tk); if (tk.v.type != T_LET) { goto ERROR_END; } Tok_simple_next(&tk); if (tk.v.type != TL_STR) { goto ERROR_END; } memcpy(buf, tk.str_val.p, tk.str_val.size); buf[tk.str_val.size] = '\0'; free(ini_buf); return; } else { // 行末まで飛ばす while (tk.v.type == T_LET || tk.v.type == TL_STR) { Tok_simple_next(&tk); } } break; case T_NL: case T_SEMICL: Tok_simple_next(&tk); break; case T_EOF: goto ERROR_END; default: fatal_errorf("Parse error at line %d (windows-tz.txt)", tk.v.line); break; } } ERROR_END: strcpy(buf, "Etc/UTC"); free(ini_buf); }
void __fastcall TForm1::Button1Click(TObject *Sender) { start=1; q_form_ini(Form1); answer=-1; //start test init_rates();// array of rates String q=read_from_file(rates[current_rate],current_q); Memo1->Text=q; start=0; }
static void read_head(struct checkpoint_head * head, int fd) { TRACE(REPLAYER_TARGET, "read ckpt head\n"); read_from_file(fd, head, sizeof(*head)); /* head checker */ if (memcmp(head->magic, CKPT_MAGIC, CKPT_MAGIC_SZ) != 0) FATAL(REPLAYER_TARGET, "checkpoint magic error\n"); TRACE(REPLAYER_TARGET, "checkpoint head magic passed\n"); TRACE(REPLAYER_TARGET, "pid=%d, tid=%d, tnr=%d\n", head->pid, head->tid, head->tnr); }
int main(int argc, char *argv[]) { char *textfile = NULL; char *pcapfile = NULL; int c; while ((c = getopt (argc, argv, "srt:p:")) != -1) { switch(c) { case 'p': optpcapfile = 1; pcapfile = optarg; break; case 't': opttextfile = 1; textfile = optarg; break; case 'r': optpretty = 0; break; case 's': optsendpackets = 1; break; case '?': default: fprintf(stderr, "usage: %s [-p <file>] [-s]\n" "\t -p <file>\t-> read USBPcap file and print all watch commands/responses it finds\n" "\t -t <file>\t-> read commands from textfile\n" "\t -r \t\t-> print raw hex (do not prettify output)\n" "\t -s \t\t-> DANGEROUS send raw commands to device\n", argv[0]); return 1; } } if(optsendpackets) { libusb_init(NULL); if (ttwatch_open(0, &watch) != TTWATCH_NoError) { fprintf(stderr, "Unable to open watch\n"); return 1; } } if (optpcapfile) read_from_pcapfile (pcapfile); else if (opttextfile) read_from_textfile (textfile); // By default read commands from standard input; else read_from_file(stdin); return 0; }
int direct_io_open(const char* path, const char* mode) { int ret = 0; int fd = 0; if(strstr(mode, "r")){ if(read_fd > 0){ errno = EPERM; return -EPERM; } read_fd = open(path, O_RDONLY | O_DIRECT); fd = DIRECT_IO_READ_FILED; DIO_TRACE("open read file \"%s\"", path); //assert(read_fd > 0); if(read_fd <= 0) { read_fd = -1; DIO_TRACE("open read file fail: \"%s\"", path); return -1; } // really open here and read a part of file ret = update_from_file(); //assert(ret == DIRECT_IO_BUFFER_SZ); if(ret != DIRECT_IO_BUFFER_SZ) { direct_io_close(fd); DIO_TRACE("read file fail: \"%s\", %d,%d(%d)", path, read_fd, fd, DIRECT_IO_READ_FILED); return -1; } strcpy(read_file, path); }else if(strstr(mode, "w")){ int sync_size = 0; if(write_fd > 0){ errno = EPERM; return -EPERM; } write_fd = open(path, O_RDWR | O_DIRECT); fd = DIRECT_IO_WRITE_FILED; DIO_TRACE("open write file \"%s\"", path); assert(write_fd > 0); // with original data sync_size = read_from_file(write_fd, s_rw_buf.write_buf, DIRECT_IO_BUFFER_SZ); lseek(write_fd, 0, SEEK_SET); strcpy(write_file, path); // reset fd pos write_pos = 0; }else{ errno = EINVAL; return -EINVAL; } return fd; }
int check_sleep() { char input_buffer[9]; input_buffer[0] = '\0'; if (read_from_file(SYS_SLEEP, 9, input_buffer) == -1) return 1; if (strcmp(input_buffer, "sleeping") == 0) return 2; return 0; }
void read_cmd(int argc, char **args, int call_type) { char *path; File *f; char *buff; uint32_t i; uint32_t len; switch (call_type) { case CALL_TYPE_HELP: puts("READ A FILE\n"); return; case CALL_TYPE_DESC: puts("PATH\n"); puts("\tPATH\tTHE PATH OF THE FILE TO READ\n"); return; } f = 0; while (argc--) { path = get_full_path(*args); if (is_path(path, strlen(path), TYPE_FILE, 0)) { f = open(path, strlen(path), 'r'); break; } free(path); } if (!f) { puts("Path not found!\n"); return; } clear_screen(); buff = (char *) palloc(); while ((len = read_from_file(f, 4096, buff))) { f->r_seek += len; for (i = 0; i < len; i++) { if (get_current() / 80 >= 21) { set_color(RED, BLACK); puts("\nPRESS ANY KEY TO CONTINUE"); set_color(LIGHT_GRAY, BLACK); getc(); clear_screen(); } putc(*(buff + i)); } } free((void *) f); pfree((void *) buff); putc('\n'); }
// Reads another chunk of a file to a buffer // @param file a pointer to a file variable static void manage_file_buffer(file_info *file) { // Read another chunk of the file to the file buffer if (file->file_count % TRANSFER_THRESHOLD_PACKETS == 0) { free(file->file_buffer); file->file_buffer = NULL; file->file_buffer = read_from_file(file->path, file->bytes_sent, get_buffer_size(file), &file->buffer_length); file->pos = file->file_buffer; } //end if } //end managa_file_buffer
int run_hook(hook_t t, process_t *process, process_return_t *ret) { int child_stdin; if (t == BEFORE_HOOK) { ret->stage = PRS_BEFORE; ret->pid = pm_execute(1, (const char*)process->before, (const char*)process->cd, (int)process->nice, (const char**)process->env, &child_stdin, (const char*)process->stdout, (const char*)process->stderr); } else if (t == AFTER_HOOK) { ret->stage = PRS_AFTER; ret->pid = pm_execute(1, (const char*)process->after, (const char*)process->cd, (int)process->nice, (const char**)process->env, &child_stdin, (const char*)process->stdout, (const char*)process->stderr); } // Check to make sure the hook executed properly ret->exit_status = wait_for_pid(ret->pid, 0); if (ret->exit_status != 0) { if (errno) { if (process->stdout) ret->stdout = read_from_file((const char*)process->stdout); if (process->stderr) { ret->stderr = read_from_file((const char*)process->stderr); } else { ret->stderr = (char*)calloc(1, sizeof(char)*strlen(strerror(errno))); strncpy(ret->stderr, strerror(errno), strlen(strerror(errno))); } } return -1; } return 0; }
int check_charge() { char input_buffer[2]; input_buffer[0] = '\0'; if (read_from_file(SYS_CHARGE, 2, input_buffer) == -1) { __android_log_write(ANDROID_LOG_ERROR, APPNAME, "Unable to get charge status from file. Cannot check profile."); return 1; } if (strcmp(input_buffer, "0") == 0) return 0; return 2; }
int check_batt_temp(int battery_temp) { char input_buffer[4]; input_buffer[0] = '\0'; if (read_from_file(SYS_BATT_TEMP, 4, input_buffer) == -1) { __android_log_write(ANDROID_LOG_ERROR, APPNAME, "Unable to get battery temperature from file. Cannot check profile."); return 1; } if (atoi(input_buffer) >= battery_temp) return 2; return 0; }
pid_t get_pid_from_file_or_retry(const char* filename, int retries) { if(retries < 0) return -1; if( file_exists(filename) ) { char *out = read_from_file(filename); char *end_of_ptr; // We never actually use this pid_t ret; if ((ret = (pid_t)strtol(out, &end_of_ptr, 10)) == 0) return -1; return ret; } else { usleep(10000); return get_pid_from_file_or_retry(filename, retries - 1); } }
/* Finds the transposition for a given ADFGX machine */ char* brute_force(adfgx* machine, const char* encoded, const char* start) { char *decoded, *header, *permutation, *permutation_array; permutation_array = read_from_file("permutations.txt"); header = strtok(permutation_array, "\n"); while ((permutation = strtok(NULL, "\n")) != NULL) { set_transposition(machine, permutation); decoded = decode_hard(machine, encoded); if (strncmp(decoded, start, strlen(start)) == 0) { free(permutation_array); return decoded; } free(decoded); } free(permutation_array); return NULL; }