//! @name Private methods //@{ // handles the current assertion. void handleAssert() { logger()( M_context); handler( M_context.level() )( M_context); }
//@see Design-page 9 void handle_recovery_req(int sd, char* clientIP){ char buf[RBUFMAX]; char log_buf[STR_MAX]; char user[STR_MAX]; char filename[STR_MAX]; char filepath[STR_MAX]; char backup_dir_path[STR_MAX]; char day[4]; char date[12]; char date_list[8][12]; unsigned int d_list_idx; unsigned int i; //char cmd[STR_MAX]; int response, len, fid; const int endQ = -1; int Q, tlen, tresp; tlen = 0; logger(SVR, "RECOVERY REQUEST START"); read(sd, &len, sizeof(len)); len = ntohl(len);// read(sd, user, len); response = isMatch(user, clientIP); tresp = htonl(response);// write(sd, &tresp, sizeof(tresp));// sprintf(backup_dir_path, "%s/%s", BACKUP_DIR, user); logger(SVR, "set path"); if(response){ //get file read(sd, &len, sizeof(len)); len = ntohl(len);// read(sd, date, len); printf("%d %s\n", len, date); d_list_idx = 0; d_list_idx = getDateList(date, date_list); for(i = 0; i <= d_list_idx; i++){ getWeekDay(date_list[i], day); sprintf(filename, "%s.tgz", date_list[i]); sprintf(filepath, "%s/%s/%s", backup_dir_path, day, filename); if( (fid = open(filepath, O_RDONLY)) < 0){ sprintf(log_buf, "There is no File : %s\n", filepath); logger(SVR, log_buf); continue; } //transmit file if it exist len = strlen(filename) + 1; tlen = htonl(len);// #if DEBUG printf("%d %d %s\n", len, tlen, filename); #endif write(sd, &tlen, sizeof(tlen)); write(sd, filename, len); while( (len = read(fid, buf, sizeof(buf))) > 0 ){ #if DEBUG printf("%d %d %d\n", len, htonl(len), sizeof(buf)); #endif tlen = htonl(len);// write(sd, &tlen, sizeof(tlen)); write(sd, buf, len); } printf("%d %d\n", endQ, htonl(endQ)); Q = htonl(endQ); write(sd, &Q, sizeof(Q)); if(fid) close(fid); } Q = htonl(endQ); write(sd, &Q, sizeof(Q)); } logger(SVR, "RECOVERY REQUEST END"); if(sd) close(sd); exit(1); }
int main() { int pid, port; //int listenfd, socketfd; char buf[MAX], clientIP[17]; int request, optval; socklen_t length; struct sockaddr_in cli_addr; struct sockaddr_in serv_addr; //child become a deamon if(fork() != 0) return 0; //parent is terminated. (void) signal(SIGCLD, SIG_IGN); (void) signal(SIGHUP, SIG_IGN); (void) setpgrp(); sigset(SIGINT, handler); set_env(); printf("The maybe backup server is operating.\n"); logger(SVR, "The maybe backup server is operating."); if((listenfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){ logger(ERR, "socket open error."); exit(1); } optval = 1; setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval)); port = PORT; serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); serv_addr.sin_port = htons(port); if(bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0){ perror("bind"); logger(ERR, "bind error"); close(listenfd); exit(1); } if(listen(listenfd, 64) < 0){ logger(ERR, "listen error."); exit(1); } logger(SVR, "This servier is listening."); while(TRUE){ length = sizeof(cli_addr); if((socketfd = accept(listenfd, (struct sockaddr *)&cli_addr, &length)) < 0){ logger(ERR, "accept error."); exit(1); } if((pid = fork()) < 0){ logger(ERR, "fork error."); exit(1); }else if(pid == 0){ close(listenfd); strcpy(clientIP, inet_ntoa(cli_addr.sin_addr)); sprintf(buf, "client[%s] is connected.\n", clientIP); logger(SVR, buf); read(socketfd, &request, sizeof(request)); request = ntohl(request); switch(request){ case USER_REQUEST: handle_user_req(socketfd, clientIP); break; case BACKUP_REQUEST: handle_backup_req(socketfd, clientIP); break; case RECOVERY_REQUEST: handle_recovery_req(socketfd, clientIP); break; } if(socketfd) close(socketfd); exit(1); //get Request //authentication //if the user is authenticated // get Request // if The rquest is BACKUP then do handle_backup_req // else if The request is RECOVERY then do handle_recovery_req //else return no and close }else close(socketfd); } return 0; }
int main(int argc, char *argv[]) { if (argc > 1) parse_args(argc, argv, lgp, mip); if (mip->shouldfork) { pid_t pid = 0; pid = fork(); if (pid < 0) { int er = errno; fprintf(stderr, "fork failed.\n"); exit(er); } if (pid > 0) exit(0); } int tstatus; /* Catch sigint (ctrl-c) */ signal(SIGINT, siginthandler); /* Catch sigterm (kill) */ signal(SIGTERM, siginthandler); /* Catch SIGUSR1, for writing control data */ signal(SIGUSR1, sigusr1handler); /* get executable name, used for logging */ dname = basename(argv[0]); strncpy(mip->dname, dname, sizeof(mip->dname)); /* get PID, also used for logging */ mip->pid = (unsigned long) getpid(); /* initialise modbus & application parameters, & set * up modbus port */ pv = mbd_init(mbp, lgp, mip); logger("starting", lgp, mip); /* kick things off with an initial reading (otherwise * the first reading won't happen until the first timer * expires) */ mbd_tick(); tstatus = start_periodic_task(mbp->msecs, mbd_tick); if (tstatus != 0) fatal("can't create timer", mbp, lgp, mip, tstatus); while (1) { if (gotsigusr1 == 1) { send_ctrl_msg(mbp, mip, lgp); gotsigusr1 = 0; } if (gotkillsig == 1) { mbd_exit(mbp, lgp, mip); unlink(mip->fifo); free(pv); exit(0); } usleep(50000); } }
/** * @brief Start the storage server. * * This is the main entry point for the storage server. It reads the * configuration file, starts listening on a port, and proccesses * commands from clients. */ int main(int argc, char *argv[]) { Table database[MAX_DATABASE_LEN]; //printf("Setting time\n");//remove time ( &rawtime ); timeinfo2 = localtime ( &rawtime ); //printf("Finished rawtime stuff\n"); //remove //printf("About to do strftime\n"); //remove strftime (buffer2,40,"Server-%Y-%m-%d-%H-%M-%S.log",timeinfo2); puts (buffer2); //printf("Finished setting time\n");//remove // Process command line arguments. // This program expects exactly one argument: the config file name. assert(argc > 0); if (argc != 2) { printf("Usage %s <config_file>\n", argv[0]); exit(EXIT_FAILURE); } char *config_file = argv[1]; // Read the config file. struct config_params params; int status = read_config(config_file, ¶ms); if (status != 0) { printf("Error processing config file.\n"); exit(EXIT_FAILURE); } n = sprintf(message, "Server on %s:%d\n", params.server_host, params.server_port); //printf("%i", n); fp = fopen(buffer2, "a+"); logger(LOGGING, fp, message); fclose(fp); // Create a socket. int listensock = socket(PF_INET, SOCK_STREAM, 0); if (listensock < 0) { printf("Error creating socket.\n"); exit(EXIT_FAILURE); } // Allow listening port to be reused if defunct. int yes = 1; status = setsockopt(listensock, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof yes); if (status != 0) { printf("Error configuring socket.\n"); exit(EXIT_FAILURE); } // Bind it to the listening port. struct sockaddr_in listenaddr; memset(&listenaddr, 0, sizeof listenaddr); listenaddr.sin_family = AF_INET; listenaddr.sin_port = htons(params.server_port); inet_pton(AF_INET, params.server_host, &(listenaddr.sin_addr)); // bind to local IP address status = bind(listensock, (struct sockaddr*) &listenaddr, sizeof listenaddr); if (status != 0) { printf("Error binding socket.\n"); exit(EXIT_FAILURE); } // Listen for connections. status = listen(listensock, MAX_LISTENQUEUELEN); if (status != 0) { printf("Error listening on socket.\n"); exit(EXIT_FAILURE); } // Listen loop. int wait_for_connections = 1; while (wait_for_connections) { // Wait for a connection. struct sockaddr_in clientaddr; socklen_t clientaddrlen = sizeof clientaddr; int clientsock = accept(listensock, (struct sockaddr*)&clientaddr, &clientaddrlen); if (clientsock < 0) { printf("Error accepting a connection.\n"); exit(EXIT_FAILURE); } n = sprintf(message, "Got a connection from %s:%d.\n", inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port); fp = fopen(buffer2, "a+"); logger(LOGGING, fp, message); fclose(fp); // Get commands from client. int wait_for_commands = 1; do { // Read a line from the client. char cmd[MAX_CMD_LEN]; int status = recvline(clientsock, cmd, MAX_CMD_LEN); if (status != 0) { // Either an error occurred or the client closed the connection. wait_for_commands = 0; } else { // Handle the command from the client. int status = handle_command(clientsock, cmd, database, params.username, params.password); if (status != 0) wait_for_commands = 0; // Oops. An error occured. } } while (wait_for_commands); // Close the connection with the client. close(clientsock); n = sprintf(message, "Closed connection from %s:%d.\n", inet_ntoa(clientaddr.sin_addr), clientaddr.sin_port); fp = fopen(buffer2, "a+"); logger(LOGGING, fp, message); fclose(fp); } // Stop listening for connections. close(listensock); return EXIT_SUCCESS; }
UIOHOOK_API void hook_set_dispatch_proc(dispatcher_t dispatch_proc) { logger(LOG_LEVEL_DEBUG, "%s [%u]: Setting new dispatch callback to %#p.\n", __FUNCTION__, __LINE__, dispatch_proc); dispatcher = dispatch_proc; }
bool constructTransaction( const AccountKeys& sender_account_keys, const std::vector<TransactionSourceEntry>& sources, const std::vector<TransactionDestinationEntry>& destinations, std::vector<uint8_t> extra, Transaction& tx, uint64_t unlock_time, Logging::ILogger& log) { LoggerRef logger(log, "construct_tx"); tx.inputs.clear(); tx.outputs.clear(); tx.signatures.clear(); tx.version = CURRENT_TRANSACTION_VERSION; tx.unlockTime = unlock_time; tx.extra = extra; KeyPair txkey = generateKeyPair(); addTransactionPublicKeyToExtra(tx.extra, txkey.publicKey); struct input_generation_context_data { KeyPair in_ephemeral; }; std::vector<input_generation_context_data> in_contexts; uint64_t summary_inputs_money = 0; //fill inputs for (const TransactionSourceEntry& src_entr : sources) { if (src_entr.realOutput >= src_entr.outputs.size()) { logger(ERROR) << "real_output index (" << src_entr.realOutput << ")bigger than output_keys.size()=" << src_entr.outputs.size(); return false; } summary_inputs_money += src_entr.amount; //KeyDerivation recv_derivation; in_contexts.push_back(input_generation_context_data()); KeyPair& in_ephemeral = in_contexts.back().in_ephemeral; KeyImage img; if (!generate_key_image_helper(sender_account_keys, src_entr.realTransactionPublicKey, src_entr.realOutputIndexInTransaction, in_ephemeral, img)) return false; //check that derived key is equal with real output key if (!(in_ephemeral.publicKey == src_entr.outputs[src_entr.realOutput].second)) { logger(ERROR) << "derived public key mismatch with output public key! " << ENDL << "derived_key:" << Common::podToHex(in_ephemeral.publicKey) << ENDL << "real output_public_key:" << Common::podToHex(src_entr.outputs[src_entr.realOutput].second); return false; } //put key image into tx input KeyInput input_to_key; input_to_key.amount = src_entr.amount; input_to_key.keyImage = img; //fill outputs array and use relative offsets for (const TransactionSourceEntry::OutputEntry& out_entry : src_entr.outputs) { input_to_key.outputIndexes.push_back(out_entry.first); } input_to_key.outputIndexes = absolute_output_offsets_to_relative(input_to_key.outputIndexes); tx.inputs.push_back(input_to_key); } // "Shuffle" outs std::vector<TransactionDestinationEntry> shuffled_dsts(destinations); std::sort(shuffled_dsts.begin(), shuffled_dsts.end(), [](const TransactionDestinationEntry& de1, const TransactionDestinationEntry& de2) { return de1.amount < de2.amount; }); uint64_t summary_outs_money = 0; //fill outputs size_t output_index = 0; for (const TransactionDestinationEntry& dst_entr : shuffled_dsts) { if (!(dst_entr.amount > 0)) { logger(ERROR, BRIGHT_RED) << "Destination with wrong amount: " << dst_entr.amount; return false; } KeyDerivation derivation; PublicKey out_eph_public_key; bool r = generate_key_derivation(dst_entr.addr.viewPublicKey, txkey.secretKey, derivation); if (!(r)) { logger(ERROR, BRIGHT_RED) << "at creation outs: failed to generate_key_derivation(" << dst_entr.addr.viewPublicKey << ", " << txkey.secretKey << ")"; return false; } r = derive_public_key(derivation, output_index, dst_entr.addr.spendPublicKey, out_eph_public_key); if (!(r)) { logger(ERROR, BRIGHT_RED) << "at creation outs: failed to derive_public_key(" << derivation << ", " << output_index << ", " << dst_entr.addr.spendPublicKey << ")"; return false; } TransactionOutput out; out.amount = dst_entr.amount; KeyOutput tk; tk.key = out_eph_public_key; out.target = tk; tx.outputs.push_back(out); output_index++; summary_outs_money += dst_entr.amount; } //check money if (summary_outs_money > summary_inputs_money) { logger(ERROR) << "Transaction inputs money (" << summary_inputs_money << ") less than outputs money (" << summary_outs_money << ")"; return false; } //generate ring signatures Hash tx_prefix_hash; getObjectHash(*static_cast<TransactionPrefix*>(&tx), tx_prefix_hash); size_t i = 0; for (const TransactionSourceEntry& src_entr : sources) { std::vector<const PublicKey*> keys_ptrs; for (const TransactionSourceEntry::OutputEntry& o : src_entr.outputs) { keys_ptrs.push_back(&o.second); } tx.signatures.push_back(std::vector<Signature>()); std::vector<Signature>& sigs = tx.signatures.back(); sigs.resize(src_entr.outputs.size()); generate_ring_signature(tx_prefix_hash, boost::get<KeyInput>(tx.inputs[i]).keyImage, keys_ptrs, in_contexts[i].in_ephemeral.secretKey, src_entr.realOutput, sigs.data()); i++; } return true; }
Bool eval_intermediate_callback(Index alg_mod, /* 0 is regular, 1 is resto */ Index iter_count, Number obj_value, Number inf_pr, Number inf_du, Number mu, Number d_norm, Number regularization_size, Number alpha_du, Number alpha_pr, Index ls_trials, UserDataPtr data) { logger("[Callback:E]intermediate_callback"); DispatchData *myowndata = (DispatchData *) data; UserDataPtr user_data = (UserDataPtr) myowndata->userdata; long result_as_long; Bool result_as_bool; PyObject *python_algmod = Py_BuildValue("i", alg_mod); PyObject *python_iter_count = Py_BuildValue("i", iter_count); PyObject *python_obj_value = Py_BuildValue("d", obj_value); PyObject *python_inf_pr = Py_BuildValue("d", inf_pr); PyObject *python_inf_du = Py_BuildValue("d", inf_du); PyObject *python_mu = Py_BuildValue("d", mu); PyObject *python_d_norm = Py_BuildValue("d", d_norm); PyObject *python_regularization_size = Py_BuildValue("d", regularization_size); PyObject *python_alpha_du = Py_BuildValue("d", alpha_du); PyObject *python_alpha_pr = Py_BuildValue("d", alpha_pr); PyObject *python_ls_trials = Py_BuildValue("i", ls_trials); PyObject *arglist = NULL; if (user_data != NULL) arglist = Py_BuildValue("(OOOOOOOOOOOO)", python_algmod, python_iter_count, python_obj_value, python_inf_pr, python_inf_du, python_mu, python_d_norm, python_regularization_size, python_alpha_du, python_alpha_pr, python_ls_trials, (PyObject *) user_data); else arglist = Py_BuildValue("(OOOOOOOOOOO)", python_algmod, python_iter_count, python_obj_value, python_inf_pr, python_inf_du, python_mu, python_d_norm, python_regularization_size, python_alpha_du, python_alpha_pr, python_ls_trials); PyObject *result = PyObject_CallObject(myowndata->eval_intermediate_callback_python, arglist); if (!result) PyErr_Print(); result_as_long = PyInt_AsLong(result); result_as_bool = (Bool) result_as_long; Py_DECREF(result); Py_CLEAR(arglist); logger("[Callback:R] intermediate_callback"); return result_as_bool; }
int main(int argc, char *argv[]) { pthread_t t_cleanup; // thread for cleaning up dead sessions. pthread_t t_healthagent; // thread for health agent. pthread_t t_cli; // thread for cli. pthread_t t_counters; // thread for performance counters. pthread_t t_memorymanager; // thread for the memory manager. struct ifaddrs *ifaddr;//, *ifa; __u32 tempIP; // int s; int i; char message[LOGSZ]; char strIP[20]; // char host[NI_MAXHOST]; char path[100] = "/etc/opennop/opennop.conf"; int tmp; __u32 packet_size = PACKET_SIZE, packet_number = PACKET_NUMBER, thr_num = DEF_THR_NUM; __u32 fpPerPkt = DEF_FP_PER_PKT, fpsFactor = DEF_FPS_FACTOR; #if defined(DEBUG) int daemonize = false; #else int daemonize = true; #endif /* Setup signal handling */ signal(SIGHUP, signal_handler); signal(SIGTERM, signal_handler); signal(SIGINT, signal_handler); signal(SIGQUIT, signal_handler); signal(SIGPIPE,SIG_IGN); int c; while ((c = getopt(argc, argv, "nh|help")) != -1) { switch (c) { case 'h': PrintUsage(argc, argv); exit(0); break; case 'n': daemonize = 0; isdaemon = false; break; default: PrintUsage(argc, argv); break; } } sprintf(message, "Initialization: %s daemon starting up.\n", DAEMON_NAME); logger(LOG_INFO, message); /* * Configuration: read the configuration file */ sprintf(message, "Configuring: reading file %s.\n", path); logger(LOG_INFO, message); tmp = configure(path, &localID, &packet_number, &packet_size, &thr_num, &fpPerPkt, &fpsFactor); if(tmp == 1){ sprintf(message, "Configuring error. EXIT\n"); logger(LOG_INFO, message); exit(EXIT_FAILURE); } sprintf(message, "Initialization: Version %s.\n", VERSION); logger(LOG_INFO, message); /* * Get the numerically highest local IP address. * This will be used as the acceleratorID. */ if (getifaddrs(&ifaddr) == -1) { sprintf(message, "Initialization: Error opening interfaces.\n"); logger(LOG_INFO, message); exit(EXIT_FAILURE); } // for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) { // loop through all interfaces. // // if (ifa->ifa_addr != NULL) { // // if (ifa->ifa_addr->sa_family == AF_INET) { // get all IPv4 addresses. // s = getnameinfo(ifa->ifa_addr, sizeof(struct sockaddr_in), // host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); // // if (s != 0) { // exit(EXIT_FAILURE); // } // // inet_pton(AF_INET, (char *) &host, &tempIP); // convert string to decimal. // // /* // * Lets fine the largest local IP, and use that as accelleratorID // * Lets also exclude 127.0.0.1 as a valid ID. // */ // if ((tempIP > localID) && (tempIP != LOOPBACKIP)) { // localID = tempIP; // } // } // end get all IPv4 addresses. // } // end ifa->ifa_addr NULL test. // } // end loop through all interfaces. if (localID == 0) { // fail if no usable IP found. inet_ntop(AF_INET, &tempIP, strIP, INET_ADDRSTRLEN); sprintf(message, "Initialization: No usable IP Address. %s\n", strIP); logger(LOG_INFO, message); exit(EXIT_FAILURE); } #if defined(DEBUG) setlogmask(LOG_UPTO(LOG_DEBUG)); openlog(DAEMON_NAME, LOG_CONS | LOG_NDELAY | LOG_PERROR | LOG_PID, LOG_USER); #else setlogmask(LOG_UPTO(LOG_INFO)); openlog(DAEMON_NAME, LOG_CONS, LOG_USER); #endif /* Our process ID and Session ID */ pid_t pid, sid; if (daemonize) { sprintf(message, "Initialization: Daemonizing the %s process.\n", DAEMON_NAME); logger(LOG_INFO, message); /* Fork off the parent process */ pid = fork(); if (pid < 0) { exit(EXIT_FAILURE); } /* If we got a good PID, then we can exit the parent process. */ if (pid > 0) { exit(EXIT_SUCCESS); } /* Change the file mode mask */ umask(0); /* Create a new SID for the child process */ sid = setsid(); if (sid < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Change the current working directory */ if ((chdir("/")) < 0) { /* Log the failure */ exit(EXIT_FAILURE); } /* Close out the standard file descriptors */ close(STDIN_FILENO); close(STDOUT_FILENO); close(STDERR_FILENO); } /* * Starting up the daemon. */ initialize_sessiontable(); if (get_workers() == 0) { set_workers(thr_num); //set_workers(sysconf(_SC_NPROCESSORS_ONLN) * 2); } #ifdef ROLLING init_common(packet_number,packet_size, fpPerPkt, fpsFactor, shareddict); init_debugd() ; #endif for (i = 0; i < get_workers(); i++) { create_worker(i); } #ifdef BASIC create_hashmap(&ht); // Create hash table #endif // Only one type of optimization can be active // assert(deduplication != compression); /* * Create the fetcher thread that retrieves * IP packets from the Netfilter Queue. */ create_fetcher(); pthread_create(&t_cleanup, NULL, cleanup_function, (void *) NULL); pthread_create(&t_healthagent, NULL, healthagent_function, (void *) NULL); pthread_create(&t_cli, NULL, cli_manager_init, (void *) NULL); pthread_create(&t_counters, NULL, counters_function, (void *) NULL); pthread_create(&t_memorymanager, NULL, memorymanager_function, (void *) NULL); sprintf(message, "[OpenNOP]: Started all threads.\n"); logger(LOG_INFO, message); /* * All the threads have been created now commands should be registered. */ register_command("show traces mask", cli_show_traces_mask, false, false); register_command("traces mask orr", cli_traces_mask_orr, true, false); register_command("traces mask and", cli_traces_mask_and, true, false); register_command("traces mask nand", cli_traces_mask_nand, true, false); register_command("reset stats in_dedup", cli_reset_stats_in_dedup, false, false); register_command("reset stats in_dedup_thread", cli_reset_stats_in_dedup, false, false); register_command("show stats in_dedup", cli_show_stats_in_dedup, false, false); register_command("show stats in_dedup_thread", cli_show_stats_in_dedup_thread, false, false); register_command("reset stats out_dedup", cli_reset_stats_out_dedup, false, false); register_command("reset stats out_dedup_thread", cli_reset_stats_out_dedup, false, false); register_command("show stats out_dedup", cli_show_stats_out_dedup, false, false); register_command("show stats out_dedup_thread", cli_show_stats_out_dedup_thread, false, false); register_command("traces enable", cli_traces_enable, true, false); register_command("traces disable", cli_traces_disable, true, false); register_command("show version", cli_show_version, false, false); register_command("show compression", cli_show_compression, false, false); register_command("show workers", cli_show_workers, false, false); register_command("show fetcher", cli_show_fetcher, false, false); register_command("show sessions", cli_show_sessionss, false, false); register_command("show deduplication", cli_show_deduplication, false, false); register_command("compression enable", cli_compression_enable, false, false); register_command("compression disable", cli_compression_disable, false, false); register_command("deduplication enable", cli_deduplication_enable, false, false); register_command("deduplication disable", cli_deduplication_disable, false, false); /* * Rejoin all threads before we exit! */ rejoin_fetcher(); sprintf(message, "[OpenNOP] Fetcher joined\n"); logger(LOG_INFO, message); pthread_join(t_cleanup, NULL); sprintf(message, "joined cleanup\n"); logger(LOG_INFO, message); pthread_join(t_healthagent, NULL); sprintf(message, "joined health\n"); logger(LOG_INFO, message); pthread_join(t_cli, NULL); sprintf(message, "joined cli\n"); logger(LOG_INFO, message); pthread_join(t_counters, NULL); sprintf(message, "joined counters\n"); logger(LOG_INFO, message); pthread_join(t_memorymanager, NULL); for (i = 0; i < get_workers(); i++) { rejoin_worker(i); } #ifdef BASIC remove_hashmap(ht); #endif clear_sessiontable(); sprintf(message, "Exiting: %s daemon exiting", DAEMON_NAME); logger(LOG_INFO, message); exit(EXIT_SUCCESS); }
Bool eval_jac_g(Index n, Number * x, Bool new_x, Index m, Index nele_jac, Index * iRow, Index * jCol, Number * values, UserDataPtr data) { logger("[Callback:E] eval_jac_g"); DispatchData *myowndata = (DispatchData *) data; UserDataPtr user_data = (UserDataPtr) myowndata->userdata; int i; long *rowd = NULL; long *cold = NULL; /* int dims[1]; */ npy_intp dims[1]; dims[0] = n; double *tempdata; if (myowndata->eval_grad_f_python == NULL) /* Why??? */ PyErr_Print(); if (values == NULL) { /* import_array (); */ import_array1(FALSE); PyObject *arrayx = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); if (!arrayx) return FALSE; PyObject *arglist; if (user_data != NULL) arglist = Py_BuildValue("(OOO)", arrayx, Py_True, (PyObject *) user_data); else arglist = Py_BuildValue("(OO)", arrayx, Py_True); PyObject *result = PyObject_CallObject(myowndata->eval_jac_g_python, arglist); if (!result) { logger("[PyIPOPT] return from eval_jac_g is null\n"); /* TODO: need to deal with reference counting here */ return FALSE; } if (!PyTuple_Check(result)) { PyErr_Print(); } PyArrayObject *row = (PyArrayObject *) PyTuple_GetItem(result, 0); PyArrayObject *col = (PyArrayObject *) PyTuple_GetItem(result, 1); if (!row || !col || !PyArray_Check(row) || !PyArray_Check(col)) { logger ("[Error] there are problems with row or col in eval_jac_g.\n"); PyErr_Print(); } rowd = (long *)row->data; cold = (long *)col->data; for (i = 0; i < nele_jac; i++) { iRow[i] = (Index) rowd[i]; jCol[i] = (Index) cold[i]; } Py_CLEAR(arrayx); Py_DECREF(result); Py_CLEAR(arglist); logger("[Callback:R] eval_jac_g(1)"); } else { PyObject *arrayx = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); if (!arrayx) return FALSE; if (new_x && myowndata->apply_new_python) { /* Call the python function to applynew */ PyObject *arg1 = Py_BuildValue("(O)", arrayx); PyObject *tempresult = PyObject_CallObject(myowndata->apply_new_python, arg1); if (tempresult == NULL) { logger("[Error] Python function apply_new returns NULL"); Py_DECREF(arg1); return FALSE; } Py_DECREF(arg1); Py_DECREF(tempresult); } PyObject *arglist; if (user_data != NULL) arglist = Py_BuildValue("(OOO)", arrayx, Py_False, (PyObject *) user_data); else arglist = Py_BuildValue("(OO)", arrayx, Py_False); PyArrayObject *result = (PyArrayObject *) PyObject_CallObject( myowndata->eval_jac_g_python, arglist); if (result == NULL) { logger("[Error] Python function eval_jac_g returns NULL"); PyErr_Print(); return FALSE; } if (!PyArray_Check(result)) { logger("[Error] Python function eval_jac_g returns non-PyArray"); Py_DECREF(result); return FALSE; } /* * Code is buggy here. We assume that result is a double * array */ assert(result->descr->type == 'd'); tempdata = (double *)result->data; for (i = 0; i < nele_jac; i++) values[i] = tempdata[i]; Py_DECREF(result); Py_CLEAR(arrayx); Py_CLEAR(arglist); logger("[Callback:R] eval_jac_g(2)"); } logger("[Callback:R] eval_jac_g"); return TRUE; }
Bool eval_h(Index n, Number * x, Bool new_x, Number obj_factor, Index m, Number * lambda, Bool new_lambda, Index nele_hess, Index * iRow, Index * jCol, Number * values, UserDataPtr data) { logger("[Callback:E] eval_h"); DispatchData *myowndata = (DispatchData *) data; UserDataPtr user_data = (UserDataPtr) myowndata->userdata; int i; npy_intp dims[1]; npy_intp dims2[1]; if (myowndata->eval_h_python == NULL) { logger("[Error] There is no eval_h assigned"); return FALSE; } if (values == NULL) { logger("[Callback:E] eval_h (1a)"); PyObject *newx = Py_True; PyObject *objfactor = Py_BuildValue("d", obj_factor); PyObject *lagrange = Py_True; PyObject *arglist; if (user_data != NULL) { arglist = Py_BuildValue( "(OOOOO)", newx, lagrange, objfactor, Py_True, (PyObject *) user_data); } else { arglist = Py_BuildValue( "(OOOO)", newx, lagrange, objfactor, Py_True); } if (arglist == NULL) { logger("[Error] failed to build arglist for eval_h"); PyErr_Print(); return FALSE; } else { logger("[Logspam] built arglist for eval_h"); } PyObject *result = PyObject_CallObject(myowndata->eval_h_python, arglist); if (result == NULL) { logger("[Error] Python function eval_h returns NULL"); PyErr_Print(); return FALSE; } else { logger("[Logspam] Python function eval_h returns non-NULL"); } int result_size = PyTuple_Size(result); if (result_size == -1) { logger("[Error] Python function eval_h returns non-PyTuple"); Py_DECREF(result); return FALSE; } if (result_size != 2) { logger("[Error] Python function eval_h returns a tuple whose len != 2"); Py_DECREF(result); return FALSE; } logger("[Callback:E] eval_h (tuple is the right length)"); PyArrayObject *row = (PyArrayObject *) PyTuple_GetItem(result, 0); PyArrayObject *col = (PyArrayObject *) PyTuple_GetItem(result, 1); long *rdata = (long *)row->data; long *cdata = (long *)col->data; for (i = 0; i < nele_hess; i++) { iRow[i] = (Index) rdata[i]; jCol[i] = (Index) cdata[i]; /* * logger("PyIPOPT_DEBUG %d, %d\n", iRow[i], * jCol[i]); */ } logger("[Callback:E] eval_h (clearing stuff now)"); Py_DECREF(objfactor); Py_DECREF(result); Py_CLEAR(arglist); logger("[Callback:R] eval_h (1b)"); } else { logger("[Callback:R] eval_h (2a)"); PyObject *objfactor = Py_BuildValue("d", obj_factor); dims[0] = n; PyObject *arrayx = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); if (!arrayx) return FALSE; if (new_x && myowndata->apply_new_python) { /* Call the python function to applynew */ PyObject *arg1 = Py_BuildValue("(O)", arrayx); PyObject *tempresult = PyObject_CallObject( myowndata->apply_new_python, arg1); if (tempresult == NULL) { logger("[Error] Python function apply_new returns NULL"); PyErr_Print(); Py_DECREF(arg1); return FALSE; } Py_DECREF(arg1); Py_DECREF(tempresult); } dims2[0] = m; PyObject *lagrangex = PyArray_SimpleNewFromData( 1, dims2, PyArray_DOUBLE, (char *)lambda); if (!lagrangex) return FALSE; PyObject *arglist; if (user_data != NULL) { arglist = Py_BuildValue( "(OOOOO)", arrayx, lagrangex, objfactor, Py_False, (PyObject *) user_data); } else { arglist = Py_BuildValue( "(OOOO)", arrayx, lagrangex, objfactor, Py_False); } PyArrayObject *result = (PyArrayObject *) PyObject_CallObject( myowndata->eval_h_python, arglist); if (result == NULL) { logger("[Error] Python function eval_h returns NULL"); PyErr_Print(); return FALSE; } if (!PyArray_Check(result)) { logger("[Error] Python function eval_h returns non-PyArray"); Py_DECREF(result); return FALSE; } double *tempdata = (double *)result->data; for (i = 0; i < nele_hess; i++) { values[i] = tempdata[i]; logger("PyDebug %lf", values[i]); } Py_CLEAR(arrayx); Py_CLEAR(lagrangex); Py_CLEAR(objfactor); Py_DECREF(result); Py_CLEAR(arglist); logger("[Callback:R] eval_h (2b)"); } return TRUE; }
Bool eval_g(Index n, Number * x, Bool new_x, Index m, Number * g, UserDataPtr data) { logger("[Callback:E] eval_g"); DispatchData *myowndata = (DispatchData *) data; UserDataPtr user_data = (UserDataPtr) myowndata->userdata; if (myowndata->eval_g_python == NULL) PyErr_Print(); /* int dims[1]; */ npy_intp dims[1]; int i; double *tempdata; dims[0] = n; // import_array (); import_array1(FALSE); /* * PyObject *arrayx = PyArray_FromDimsAndData(1, dims, PyArray_DOUBLE * , (char*) x); */ PyObject *arrayx = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); if (!arrayx) return FALSE; if (new_x && myowndata->apply_new_python) { /* Call the python function to applynew */ PyObject *arg1 = Py_BuildValue("(O)", arrayx); PyObject *tempresult = PyObject_CallObject( myowndata->apply_new_python, arg1); if (tempresult == NULL) { logger("[Error] Python function apply_new returns NULL"); PyErr_Print(); Py_DECREF(arg1); return FALSE; } Py_DECREF(arg1); Py_DECREF(tempresult); } PyObject *arglist; if (user_data != NULL) arglist = Py_BuildValue("(OO)", arrayx, (PyObject *) user_data); else arglist = Py_BuildValue("(O)", arrayx); PyArrayObject *result = (PyArrayObject *) PyObject_CallObject( myowndata->eval_g_python, arglist); if (result == NULL) { logger("[Error] Python function eval_g returns NULL"); PyErr_Print(); return FALSE; } if (!PyArray_Check(result)) { logger("[Error] Python function eval_g returns non-PyArray"); Py_DECREF(result); return FALSE; } tempdata = (double *)result->data; for (i = 0; i < m; i++) { g[i] = tempdata[i]; } Py_DECREF(result); Py_CLEAR(arrayx); Py_CLEAR(arglist); logger("[Callback:R] eval_g"); return TRUE; }
Bool eval_f(Index n, Number * x, Bool new_x, Number * obj_value, UserDataPtr data) { logger("[Callback:E] eval_f"); npy_intp dims[1]; dims[0] = n; DispatchData *myowndata = (DispatchData *) data; UserDataPtr user_data = (UserDataPtr) myowndata->userdata; // import_array (); import_array1(FALSE); PyObject *arrayx = PyArray_SimpleNewFromData(1, dims, PyArray_DOUBLE, (char *)x); if (!arrayx) return FALSE; if (new_x && myowndata->apply_new_python) { /* Call the python function to applynew */ PyObject *arg1; arg1 = Py_BuildValue("(O)", arrayx); PyObject *tempresult = PyObject_CallObject( myowndata->apply_new_python, arg1); if (tempresult == NULL) { logger("[Error] Python function apply_new returns NULL"); PyErr_Print(); Py_DECREF(arg1); return FALSE; } Py_DECREF(arg1); Py_DECREF(tempresult); } PyObject *arglist; if (user_data != NULL) { arglist = Py_BuildValue("(OO)", arrayx, (PyObject *) user_data); } else { arglist = Py_BuildValue("(O)", arrayx); } PyObject *result = PyObject_CallObject(myowndata->eval_f_python, arglist); if (result == NULL) { logger("[Error] Python function eval_f returns NULL"); PyErr_Print(); Py_DECREF(arrayx); Py_CLEAR(arglist); return FALSE; } *obj_value = PyFloat_AsDouble(result); if (PyErr_Occurred()) { logger("[Error] Python function eval_f returns non-PyFloat"); PyErr_Print(); Py_DECREF(result); Py_DECREF(arrayx); Py_CLEAR(arglist); return FALSE; } Py_DECREF(result); Py_DECREF(arrayx); Py_CLEAR(arglist); logger("[Callback:R] eval_f"); return TRUE; }
void dns_store::rpc_onover() { logger("store domain lookup results %s!", ok_ ? "OK" : "Failed"); callback_.nslookup_finish(dbpath_.empty() ? NULL : dbpath_.c_str()); delete this; }
void master_service::proc_on_listen(acl::server_socket& ss) { logger(">>>listen %s ok<<<", ss.get_addr()); }
int main(int argc, char *argv[]) { //See http://doc.qt.io/qt-5/qopenglwidget.html#opengl-function-calls-headers-and-qopenglfunctions /** Calling QSurfaceFormat::setDefaultFormat() before constructing the QApplication instance is mandatory on some platforms (for example, OS X) when an OpenGL core profile context is requested. This is to ensure that resource sharing between contexts stays functional as all internal contexts are created using the correct version and profile. **/ { QSurfaceFormat format = QSurfaceFormat::defaultFormat(); format.setSwapBehavior(QSurfaceFormat::DoubleBuffer); format.setStencilBufferSize(0); #ifdef CC_GL_WINDOW_USE_QWINDOW format.setStereo(true); #endif #ifdef Q_OS_MAC format.setStereo(false); format.setVersion( 2, 1 ); format.setProfile( QSurfaceFormat::CoreProfile ); #endif #ifdef QT_DEBUG format.setOption(QSurfaceFormat::DebugContext); #endif QSurfaceFormat::setDefaultFormat(format); } ccApplication a(argc, argv); //Locale management { //Force 'english' locale so as to get a consistent behavior everywhere QLocale locale = QLocale(QLocale::English); locale.setNumberOptions(QLocale::c().numberOptions()); QLocale::setDefault(locale); #ifdef Q_OS_UNIX //We reset the numeric locale for POSIX functions //See http://qt-project.org/doc/qt-5/qcoreapplication.html#locale-settings setlocale(LC_NUMERIC, "C"); #endif } #ifdef USE_VLD VLDEnable(); #endif #ifdef Q_OS_MAC // This makes sure that our "working directory" is not within the application bundle QDir appDir = QCoreApplication::applicationDirPath(); if ( appDir.dirName() == "MacOS" ) { appDir.cdUp(); appDir.cdUp(); appDir.cdUp(); QDir::setCurrent( appDir.absolutePath() ); } #endif if (!QGLFormat::hasOpenGL()) { QMessageBox::critical(0, "Error", "This application needs OpenGL to run!"); return EXIT_FAILURE; } if ((QGLFormat::openGLVersionFlags() & QGLFormat::OpenGL_Version_2_1) == 0) { QMessageBox::critical(0, "Error", "This application needs OpenGL 2.1 at least to run!"); return EXIT_FAILURE; } //common data initialization ccTimer::Init(); FileIOFilter::InitInternalFilters(); //load all known I/O filters (plugins will come later!) ccNormalVectors::GetUniqueInstance(); //force pre-computed normals array initialization ccColorScalesManager::GetUniqueInstance(); //force pre-computed color tables initialization ccViewer w/*(0,Qt::Window|Qt::CustomizeWindowHint)*/; #ifdef Q_OS_MAC a.setViewer( &w ); #endif //register minimal logger to display errors ccViewerLog logger(&w); ccLog::RegisterInstance(&logger); w.show(); //files to open are passed as argument if (argc > 1) { //parse arguments QStringList filenames; int i = 1; while ( i < argc) { QString argument = QString(argv[i++]).toUpper(); //Argument '-WIN X Y W H' (to set window size and position) if (argument.toUpper() == "-WIN") { bool ok = true; if (i+3 < argc) { bool converionOk; int x = QString(argv[i ]).toInt(&converionOk); ok &= converionOk; int y = QString(argv[i+1]).toInt(&converionOk); ok &= converionOk; int width = QString(argv[i+2]).toInt(&converionOk); ok &= converionOk; int height = QString(argv[i+3]).toInt(&converionOk); ok &= converionOk; i += 4; if (ok) { //change window position and size w.move(x,y); w.resize(width,height); } } if (!ok) { ccLog::Warning("Invalid arguments! 4 integer values are expected after '-win' (X Y W H)"); break; } } else if (argument == "-TOP") { w.setWindowFlags(w.windowFlags() | Qt::CustomizeWindowHint | Qt::WindowStaysOnTopHint); w.show(); } else //any other argument is assumed to be a filename (that will we try to load) { filenames << argument; } } if (!filenames.empty()) w.addToDB(filenames); } #ifdef Q_OS_MAC // process events to load any files on the command line QCoreApplication::processEvents(); #endif w.checkForLoadedEntities(); int result = a.exec(); //release global structures FileIOFilter::UnregisterAll(); return result; }
void master_service::proc_on_exit(void) { logger(">>>proc_on_exit<<<"); }
static void sssp_bfs(void) { avl_node_t *node, *next, *to; edge_t *e; node_t *n; list_t *todo_list; list_node_t *from, *todonext; bool indirect; char *name; char *address, *port; char *envp[7]; int i; todo_list = list_alloc(NULL); /* Clear visited status on nodes */ for(node = node_tree->head; node; node = node->next) { n = node->data; n->status.visited = false; n->status.indirect = true; } /* Begin with myself */ myself->status.visited = true; myself->status.indirect = false; myself->nexthop = myself; myself->via = myself; list_insert_head(todo_list, myself); /* Loop while todo_list is filled */ for(from = todo_list->head; from; from = todonext) { /* "from" is the node from which we start */ n = from->data; for(to = n->edge_tree->head; to; to = to->next) { /* "to" is the edge connected to "from" */ e = to->data; if(!e->reverse) continue; /* Situation: / / ----->(n)---e-->(e->to) \ \ Where e is an edge, (n) and (e->to) are nodes. n->address is set to the e->address of the edge left of n to n. We are currently examining the edge e right of n from n: - If edge e provides for better reachability of e->to, update e->to and (re)add it to the todo_list to (re)examine the reachability of nodes behind it. */ indirect = n->status.indirect || e->options & OPTION_INDIRECT; if(e->to->status.visited && (!e->to->status.indirect || indirect)) continue; e->to->status.visited = true; e->to->status.indirect = indirect; e->to->nexthop = (n->nexthop == myself) ? e->to : n->nexthop; e->to->via = indirect ? n->via : e->to; e->to->options = e->options; if(e->to->address.sa.sa_family == AF_UNSPEC && e->address.sa.sa_family != AF_UNKNOWN) update_node_udp(e->to, &e->address); list_insert_tail(todo_list, e->to); } todonext = from->next; list_delete_node(todo_list, from); } list_free(todo_list); /* Check reachability status. */ for(node = node_tree->head; node; node = next) { next = node->next; n = node->data; if(n->status.visited != n->status.reachable) { n->status.reachable = !n->status.reachable; if(n->status.reachable) { ifdebug(TRAFFIC) logger(LOG_DEBUG, "Node %s (%s) became reachable", n->name, n->hostname); } else { ifdebug(TRAFFIC) logger(LOG_DEBUG, "Node %s (%s) became unreachable", n->name, n->hostname); } /* TODO: only clear status.validkey if node is unreachable? */ n->status.validkey = false; n->last_req_key = 0; n->maxmtu = MTU; n->minmtu = 0; n->mtuprobes = 0; if(n->mtuevent) { event_del(n->mtuevent); n->mtuevent = NULL; } xasprintf(&envp[0], "NETNAME=%s", netname ? : ""); xasprintf(&envp[1], "DEVICE=%s", device ? : ""); xasprintf(&envp[2], "INTERFACE=%s", iface ? : ""); xasprintf(&envp[3], "NODE=%s", n->name); sockaddr2str(&n->address, &address, &port); xasprintf(&envp[4], "REMOTEADDRESS=%s", address); xasprintf(&envp[5], "REMOTEPORT=%s", port); envp[6] = NULL; execute_script(n->status.reachable ? "host-up" : "host-down", envp); xasprintf(&name, n->status.reachable ? "hosts/%s-up" : "hosts/%s-down", n->name); execute_script(name, envp); free(name); free(address); free(port); for(i = 0; i < 6; i++) free(envp[i]); subnet_update(n, NULL, n->status.reachable); if(!n->status.reachable) update_node_udp(n, NULL); else if(n->connection) send_ans_key(n); } }
//-------------------------------------------------------------------------------- bool DaemonCommandsHandler::print_pool_sh(const std::vector<std::string>& args) { logger(Logging::INFO) << "Pool state: " << ENDL << m_core.print_pool(true); return true; }
static void mst_kruskal(void) { avl_node_t *node, *next; edge_t *e; node_t *n; connection_t *c; int nodes = 0; int safe_edges = 0; bool skipped; /* Clear MST status on connections */ for(node = connection_tree->head; node; node = node->next) { c = node->data; c->status.mst = false; } /* Do we have something to do at all? */ if(!edge_weight_tree->head) return; ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Running Kruskal's algorithm:"); /* Clear visited status on nodes */ for(node = node_tree->head; node; node = node->next) { n = node->data; n->status.visited = false; nodes++; } /* Starting point */ for(node = edge_weight_tree->head; node; node = node->next) { e = node->data; if(e->from->status.reachable) { e->from->status.visited = true; break; } } /* Add safe edges */ for(skipped = false, node = edge_weight_tree->head; node; node = next) { next = node->next; e = node->data; if(!e->reverse || e->from->status.visited == e->to->status.visited) { skipped = true; continue; } e->from->status.visited = true; e->to->status.visited = true; if(e->connection) e->connection->status.mst = true; if(e->reverse->connection) e->reverse->connection->status.mst = true; safe_edges++; ifdebug(SCARY_THINGS) logger(LOG_DEBUG, " Adding edge %s - %s weight %d", e->from->name, e->to->name, e->weight); if(skipped) { skipped = false; next = edge_weight_tree->head; continue; } } ifdebug(SCARY_THINGS) logger(LOG_DEBUG, "Done, counted %d nodes and %d safe edges.", nodes, safe_edges); }
void sayNoise(const char* sounds,const int8_t* modifier){ // phonemes has list of sound bytes uint8_t phonemeIn, // offset into text byte2, modifierIn; // offset into stuff in modifier int8_t punctuationPitchDelta; // change in pitch due to fullstop or question mark SOUND_ACTION action; char phoneme; const SOUND_INDEX* soundIndex; uint8_t sound1Num; // Sound data for the current phoneme uint8_t sound2Num; // Sound data for the next phoneme uint8_t sound2Stop; // Where the second sound should stop int8_t pitch1; // pitch for the first sound int8_t pitch2; // pitch for the second sound short i; uint8_t sound1Duration; // the duration for sound 1. 0 to 255. #ifdef _LOG_ { int p=0; loggerP(PSTR("Data:")); logger(sounds); loggerCRLF(); loggerP(PSTR("Modifier:")); while(sounds[p]){ uint8_t m = modifier[p]; uint8_t h; h = m>>4; loggerc( (char)((h<=9) ? (h+'0') : (h-10+'A')) ); // hex char h=m & 15; loggerc( (char)((h<=9) ? (h+'0') : (h-10+'A')) ); // hex char loggerc(','); m = modifier[p+1]; h = m>>4; loggerc( (char)((h<=9) ? (h+'0') : (h-10+'A')) ); // hex char h=m & 15; loggerc( (char)((h<=9) ? (h+'0') : (h-10+'A')) ); // hex char loggerc(','); p+=2; } loggerCRLF(); } #endif soundOn(); // _630C // action=ACTION_NO_ACTION; punctuationPitchDelta=0; //Q19 for(phonemeIn=0,modifierIn=0;sounds[phonemeIn]!=0; phonemeIn+=2, modifierIn+=2){ uint8_t duration; // duration from text line uint8_t SoundPos; // offset into sound data uint8_t fadeSpeed=0; // Fade speed between the two sounds. 0 to 255 action=ACTION_NO_ACTION; phoneme=sounds[phonemeIn]; if(phoneme=='z'){ delay(15); goto nextPhoneme; }else if(phoneme=='#'){ goto nextPhoneme; }else{ // Collect info on sound 1 soundIndex = &SoundIndex[phoneme - 'A']; sound1Num = pgm_read_byte(&soundIndex->SoundNumber); action = pgm_read_byte(&soundIndex->action); byte2 = pgm_read_byte(&soundIndex->byte2); duration = sounds[phonemeIn+1] - '0'; // Get duration from the input line if(duration!=1){ duration<<=1; } duration += 6; // scaled duration from the input line (at least 6) sound2Stop = 0x40 / 2; pitch1 = modifier[modifierIn]; if(modifier[modifierIn + 1]==0 || pitch1==-1){ pitch1 = 10; duration -= 6; }else if(modifier[modifierIn + 1]=='0' || duration==6){ duration -= 6; } //q8 pitch2 = modifier[modifierIn+2]; if(modifier[modifierIn + 3]==0 || pitch2 == -1){ pitch2 = 10; } if(action<ACTION_NO_ACTION){ //sound1Num = 0; random(); sound2Stop=(0x40 / 2)+2; }else if(action==ACTION_FADE_IN){ uint8_t volume; // volume mask #ifdef _LOG_ // loggerP(PSTR("\nA *******")); // logger_uint8(duration); // loggerCRLF(); #endif volume = (duration==6) ? 15 : 1; /// volume mask for(duration <<= 2; duration>0; duration--){ playTone(sound1Num,random(),8,12,17, volume); // Increase the volume if(++volume==16){ volume = 15; // full volume from now on } } goto nextPhoneme; }else if(action == ACTION_PAUSE){ delay(25); } } // 6186 pitch1 = pitch1 + default_pitch + punctuationPitchDelta; if(pitch1<1){ pitch1=1; } pitch2 = pitch2 + default_pitch + punctuationPitchDelta; if(pitch2<1){ pitch2=1; } // get next phoneme phoneme=sounds[phonemeIn + 2]; if(phoneme==0 || phoneme=='z'){ if(duration==1){ delay(60); } phoneme='a'; // change to a pause }else{ // s6 if(byte2 != 1){ // Get the average of byte2 for the two phonemes byte2 = (byte2 + pgm_read_byte(&SoundIndex[phoneme-'A'].byte2))>>1; } if(action < ACTION_NO_ACTION || pgm_read_byte(&SoundIndex[phoneme-'A'].action) != ACTION_NO_ACTION){ phoneme ='a'; // change to a pause } } // S10 - 61e5 sound2Num = pgm_read_byte(&SoundIndex[phoneme-'A'].SoundNumber); sound1Duration = 0x80; // play half of sound 1 if(sound2Num==sound1Num){ byte2 = duration; } // S11 if( (byte2>>1) == 0 ){ sound1Duration = 0xff; // play all of sound 1 }else{
/* * This replaces cli_process_message(). * It can execute multiple commands that share the same name. */ int execute_commands(int client_fd, const char *command_name, int d_len) { char *token, *cp, *saved_token; int parametercount = 0, idx = 0; int shutdown = CLI_ERROR; char **parameters = NULL; //dynamic array of pointers to tokens that are parameters //char **tempparameters = NULL; //char *parameter = NULL; struct command_head *currentnode = NULL; struct command *currentcommand = NULL; struct command *executedcommand = NULL; char message[LOGSZ]; sprintf(message, "CLI: Begin processing a command.\n"); logger(LOG_INFO, message); if((head == NULL) || (head->next == NULL)) { /* * Cannot execute any commands if there are none. */ sprintf(message, "CLI: No known commands.\n"); logger(LOG_INFO, message); shutdown = CLI_INV_CMD; return shutdown; } /* * Make writable copy of *command_name for separating into GNU string TOKENS. * The TOKENS are separated by spaces. */ cp = strdup(command_name); /* * Initialize TOKEN. * The delimiters are globally defined for consistency. */ token = strtok_r(cp, delimiters, &saved_token); currentnode = head; while((token != NULL) && (executedcommand == NULL)) { /* Sharwan: We should check first, if the command is help,Help or ? * Help in any case is good , but other commands are not */ if((!strcasecmp(token,"help")) || (!strcmp(token,"?"))) { cli_node_help(client_fd, currentnode); break; } currentcommand = find_command(currentnode,token); if(currentcommand == NULL) { /* * We didn't find any commands. * Show help for the current node then break. * Need the help function to accept the currentnode as a parameter. */ sprintf(message, "CLI: Cound'nt find the command.\n"); logger(LOG_INFO, message); /* If we're exiting from this point, free the allocations made */ if (cp) { free(cp); cp = NULL; } shutdown = CLI_INV_CMD; break; } else { /* We've got some command or token */ if(currentcommand->child.next != NULL) { sprintf(message, "CLI: Command [%s] has children.\n", token); logger(LOG_INFO, message); currentnode = ¤tcommand->child; currentcommand = NULL; } else { /* * We found a command in this node. * There are no other child nodes so its the last one. */ sprintf(message, "CLI: Locating [%s] command .\n", token); logger(LOG_INFO, message); while((executedcommand == NULL) && (currentcommand != NULL)) { sprintf(message, "CLI: Current command [%s].\n", currentcommand->command ); logger(LOG_INFO, message); if(currentcommand->command_handler == NULL) { sprintf(message, "CLI: Command has no handler.\n"); logger(LOG_INFO, message); } if((!strcmp(currentcommand->command,token)) && (currentcommand->command_handler != NULL)) { if(currentcommand->hasparams == true) { sprintf(message, "CLI: Command has parameters.\n"); logger(LOG_INFO, message); /* * NOTE: I found that you cannot pass *cp because its modified by strtok_r() * The modification removed the " " delimiter and must replace it with a \0 * to terminate that TOKEN. This prevents *cp from being re-parsed as a parameter. * As a solution we can pass the original command_name and try to process it more then. * Another solution might to be make another copy of command_name then remove the * original command somehow to pass only the remaining arguments/parameters. * This will require saving the whole original command in the command structure * so it can be referenced again. * * UPDATE: I posted a question at LinuxQuestions about this. * One very good idea is to create a dynamic array of the TOKENs and * pass that to the function as the parameter. * http://www.linuxquestions.org/questions/programming-9/parse-string-tokens-and-pass-remaining-as-parameter-4175468498/#post4984764 */ if(token != NULL) { if (strlen(saved_token) == 0) { sprintf(message, "CLI: Command has no parameters.\n"); logger(LOG_INFO, message); shutdown = (currentcommand->command_handler)(client_fd, NULL, 0); } else { char *temp_token = (char *) malloc (strlen(saved_token) + 1); memcpy(temp_token, saved_token, strlen(saved_token)); temp_token[strlen(saved_token)] = '\0'; idx = detect_delim_count(temp_token, delimiters); if (temp_token) free(temp_token); parameters = malloc((idx + 1 ) * sizeof (char *)); if ( NULL == parameters) { fprintf(stdout, "CLI: Couldn't allocate sufficient memory . Exiting \n"); exit(1); } for( parametercount = 0 , token = strtok(saved_token, " "); parametercount <= idx ; ++parametercount , token = strtok(NULL, " ")) { parameters[parametercount] = calloc(30 , strlen(token) + 1); if ( NULL == parameters[parametercount]) { fprintf(stdout,"CLI: Couldn't allocate sufficient memory. Exiting \n"); exit(1); } strncpy(*(parameters + parametercount), token, strlen(token)); } /* Execute the command finally */ shutdown = (currentcommand->command_handler)(client_fd, parameters, parametercount); } } } else { /* * We might want to verify no other TOKENs are left. * If the command has no params none should have been given. */ sprintf(message, "CLI: Command has no parameters.\n"); logger(LOG_INFO, message); shutdown = (currentcommand->command_handler)(client_fd, NULL, 0); } executedcommand = currentcommand; } else { shutdown = CLI_ERR_CMD; sprintf(message, "CLI: Command did not match.\n"); logger(LOG_INFO, message); } currentcommand = currentcommand->next; } /* * Finished executing all commands in the node. */ if (parameters != NULL) { for (parametercount = 0 ; parametercount <= idx; ++parametercount) if (parameters[parametercount]) free(parameters[parametercount]); free(parameters); /* If we directly do this, we'll get bad SIGSEGV's */ } } } token = strtok_r(NULL, delimiters, &saved_token); //Fetch the next TOKEN of the command. if (token == NULL && shutdown == CLI_ERROR) { cli_node_help(client_fd, currentnode); } } if (cp) { free(cp); cp = NULL; } /* if(shutdown != 1){ // Don't show the last prompt if we are done. cli_prompt(client_fd); } */ // char msg[MAX_BUFFER_SIZE] = { 0 }; // sprintf(msg, "ENDOFCOMMAND\n"); // printf("client_fd: %d, mensaje: %sEOV\n", client_fd, msg); // cli_send_feedback(client_fd, msg); return shutdown; }
int handle_command(int sock, char *cmd, Table* database, char* username, char* password) { n = sprintf(message, "Processing command '%s'\n", cmd); fp = fopen(buffer2, "a+"); logger(LOGGING, fp, message); // replace LOG commands with logger() calls fclose(fp); // For now, just send back the command to the client. int isReadingCMD=0; //boolean that indicated whether it is reading the command indicator (AUTH, SET, GET) char* split, arg1, arg2, arg3; split=strtok(cmd, " "); if(split=="AUTH") { arg1=strtok(NULL, " ");//Get username arg2=strtok(NULL, " ");//Get password if(username==arg1&&password==arg2){ sendall(sock, arg1, strlen(arg1)); return 0; } else return -1; } else if(split=="GET") { arg1=strtok(NULL, " ");//Get name of table arg2=strtok(NULL, " ");//Get key of entry Table* table=table_search(arg1, database); if(table){ Entry* entry=entry_search(arg2, table->entry); if(entry){ sendall(sock, entry->value, strlen(entry->value)); } } } else if(split=="SET") { arg1=strtok(NULL, " ");//Get name of table arg2=strtok(NULL, " ");//Get key of entry arg3=strtok(NULL, " ");//Get value to set Table* table=table_search(arg1, database); if(!table){ int i; for(i=0; i<MAX_DATABASE_LEN; i++){ if(database[i].name==""){ table=&database[i]; break; } } } table->name=arg1; Entry* entry=entry_search(arg2, table->entry); if(!entry){ int i; for(i=0; i<MAX_DATABASE_LEN; i++){ if(table->entry[i].key==""){ entry=&(table->entry[i]); break; } } } entry->key=arg2; entry->value=arg3; sendall(sock, entry->value, strlen(entry->value)); } /* sendall(sock, cmd, strlen(cmd)); sendall(sock, "\n", 1);*/ return 0; }
int register_command(const char *command_name, t_commandfunction handler_function, bool hasparams, bool hidden) { char *token, *cp, *saved_token; struct command_head *currentnode = NULL; struct command *currentcommand = NULL; char message[LOGSZ]; pthread_mutex_lock(&lock); sprintf(message, "CLI: Begin registering [%s] command.\n", command_name); logger(LOG_INFO, message); if(head == NULL) { head = (struct command_head *) malloc (sizeof (struct command_head)); head->next = NULL; head->prev = NULL; pthread_mutex_init(&head->lock,NULL); } /* * Make writable copy of *command_name for separating into GNU string TOKENS. * The TOKENS are separated by spaces. */ cp = strdup(command_name); /* * Initialize TOKEN. * The delimiters are globally defined for consistency. */ token = strtok_r(cp, delimiters, &saved_token); currentnode = head; while(token != NULL) { pthread_mutex_lock(¤tnode->lock); //Prevent race condition when saving command tree. sprintf(message, "CLI: Register [%s] token.\n",token); logger(LOG_INFO, message); /* * Search the current node for a * command matching the current TOKEN. */ currentcommand = find_command(currentnode,token); if(currentcommand != NULL) { /*! *Found the command for the current TOKEN. *Set it as the current node and search it for the next TOKEN. */ sprintf(message, "CLI: Found an existing token.\n"); logger(LOG_INFO, message); } else { /* * Did not find the command for the current TOKEN * We have to create it. */ sprintf(message, "CLI: Did not find an existing token.\n"); logger(LOG_INFO, message); currentcommand = allocate_command(); currentcommand->command = token; if(currentnode->next == NULL) { sprintf(message, "CLI: Creating first command in node.\n"); logger(LOG_INFO, message); currentnode->next = currentcommand; currentnode->prev = currentcommand; } else { sprintf(message, "CLI: Creating new command in node.\n"); logger(LOG_INFO, message); currentnode->prev->next = currentcommand; currentcommand->prev = currentnode->prev; currentnode->prev = currentcommand; } } pthread_mutex_unlock(¤tnode->lock); currentnode = ¤tcommand->child; token = strtok_r(NULL, delimiters, &saved_token); //Fetch the next TOKEN of the command. } //This was the last TOKEN of the command so assign the function here. if(currentcommand != NULL) { currentcommand->command_handler = handler_function; currentcommand->hasparams = hasparams; currentcommand->hidden = hidden; } pthread_mutex_unlock(&lock); return 0; }
bool pColScanStep::isEmptyVal(const uint8_t *val8) const { const int width = fColType.colWidth; switch (fColType.colDataType) { case CalpontSystemCatalog::UTINYINT: { return(*val8 == joblist::UTINYINTEMPTYROW); } case CalpontSystemCatalog::USMALLINT: { const uint16_t *val16 = reinterpret_cast<const uint16_t *>(val8); return(*val16 == joblist::USMALLINTEMPTYROW); } case CalpontSystemCatalog::UMEDINT: case CalpontSystemCatalog::UINT: { const uint32_t *val32 = reinterpret_cast<const uint32_t *>(val8); return(*val32 == joblist::UINTEMPTYROW); } case CalpontSystemCatalog::UBIGINT: { const uint64_t *val64 = reinterpret_cast<const uint64_t *>(val8); return(*val64 == joblist::BIGINTEMPTYROW); } case CalpontSystemCatalog::FLOAT: case CalpontSystemCatalog::UFLOAT: { const uint32_t *val32 = reinterpret_cast<const uint32_t *>(val8); return(*val32 == joblist::FLOATEMPTYROW); } case CalpontSystemCatalog::DOUBLE: case CalpontSystemCatalog::UDOUBLE: { const uint64_t *val64 = reinterpret_cast<const uint64_t *>(val8); return(*val64 == joblist::DOUBLEEMPTYROW); } case CalpontSystemCatalog::CHAR: case CalpontSystemCatalog::VARCHAR: case CalpontSystemCatalog::DATE: case CalpontSystemCatalog::DATETIME: if (width == 1) { return(*val8 == joblist::CHAR1EMPTYROW); } else if (width == 2) { const uint16_t *val16 = reinterpret_cast<const uint16_t *>(val8); return(*val16 == joblist::CHAR2EMPTYROW); } else if (width <= 4) { const uint32_t *val32 = reinterpret_cast<const uint32_t *>(val8); return(*val32 == joblist::CHAR4EMPTYROW); } else if (width <= 8) { const uint64_t *val64 = reinterpret_cast<const uint64_t *>(val8); return(*val64 == joblist::CHAR8EMPTYROW); } default: break; } switch (width) { case 1: { return(*val8 == joblist::TINYINTEMPTYROW); } case 2: { const uint16_t *val16 = reinterpret_cast<const uint16_t *>(val8); return(*val16 == joblist::SMALLINTEMPTYROW); } case 4: { const uint32_t *val32 = reinterpret_cast<const uint32_t *>(val8); return(*val32 == joblist::INTEMPTYROW); } case 8: { const uint64_t *val64 = reinterpret_cast<const uint64_t *>(val8); return(*val64 == joblist::BIGINTEMPTYROW); } default: MessageLog logger(LoggingID(28)); logging::Message::Args colWidth; Message msg(33); colWidth.add(width); msg.format(colWidth); logger.logErrorMessage(msg); return false; } return false; }
int main(int argc, char** argv) { ctkLogger logger ( "org.commontk.dicom.DICOMRetieveApp" ); // Set the DCMTK log level to debug ctk::setDICOMLogLevel(ctkErrorLogLevel::Debug); if (argc < 9) { print_usage(); return EXIT_FAILURE; } QCoreApplication app(argc, argv); QTextStream out(stdout); QString StudyUID ( argv[1] ); QDir OutputDirectory ( argv[2] ); QString CallingAETitle ( argv[3] ); bool ok; QString CalledAETitle ( argv[4] ); QString Host ( argv[5] ); int CalledPort = QString ( argv[6] ).toInt ( &ok ); if ( !ok ) { std::cerr << "Could not convert " << argv[7] << " to an integer for the calledPoint" << std::endl; print_usage(); return EXIT_FAILURE; } QString MoveDestinationAETitle ( argv[8] ); ctkDICOMRetrieve retrieve; retrieve.setCallingAETitle ( CallingAETitle ); retrieve.setCalledAETitle ( CalledAETitle ); retrieve.setPort ( CalledPort ); retrieve.setHost ( Host ); retrieve.setMoveDestinationAETitle ( MoveDestinationAETitle ); logger.info ( "StudyUID: " + StudyUID + "\n" + "OutputDirectory: " + OutputDirectory.absolutePath() + "\n" + "CallingAETitle: " + CallingAETitle + "\n" + "CalledAEtitle: " + CalledAETitle + "\n" + "Host: " + Host + "\n" + "CalledPort: " + QString::number ( CalledPort ) + "\n" ); QSharedPointer<ctkDICOMDatabase> dicomDatabase = QSharedPointer<ctkDICOMDatabase> (new ctkDICOMDatabase); dicomDatabase->openDatabase( OutputDirectory.absoluteFilePath(QString("ctkDICOM.sql")) ); retrieve.setDatabase( dicomDatabase ); logger.info ( "Starting to retrieve" ); try { retrieve.moveStudy ( StudyUID ); } catch (std::exception e) { logger.error ( "Retrieve failed" ); return EXIT_FAILURE; } logger.info ( "Retrieve success" ); return EXIT_SUCCESS; }
void handle_backup_req(int sd, char* clientIP){ char buf[BUFSIZE+100]; char log_buf[STR_MAX]; char user[STR_MAX]; char filename[STR_MAX]; char filepath[STR_MAX]; char backup_dir_path[STR_MAX]; char day[4]; char date[12]; char subject[STR_MAX]; char cmd[STR_MAX]; int response, len, fid; FILE* fp; int nsize, fsize, fsize2, fpsize, fpsize2; const int endQ = -1; int Q, tlen, tresp, i; tlen = 0; Q = -1; logger(SVR, "BACKUP REQUEST START"); read(sd, &len, sizeof(len)); len = ntohl(len);// read(sd, user, len); response = isMatch(user, clientIP); tresp = htonl(response);// write(sd, &tresp, sizeof(tresp)); if(response){ //get file read(sd, &len, sizeof(len)); len = ntohl(len);// read(sd, day, len); read(sd, &len, sizeof(len)); len = ntohl(len); // read(sd, date, len); check_create_dir(backup_dir_path); sprintf(backup_dir_path, "%s/%s", BACKUP_DIR, user); check_create_dir(backup_dir_path); sprintf(backup_dir_path, "%s/%s", backup_dir_path, day); check_create_dir(backup_dir_path); sprintf(log_buf, "Set Backup directory : %s", backup_dir_path); logger(SVR, log_buf); //check and create directory while(TRUE){ read(sd, &len, sizeof(len)); len = ntohl(len);// if(len == endQ) break; read(sd, filename, len); #if DEBUE printf("%d %d filename : %s\n", len, endQ, filename); #endif sprintf(log_buf, "Get filename from %s[%s] : %s\n", user, clientIP, filename); logger(SVR, log_buf); sprintf(filepath, "%s/%s", backup_dir_path, filename); fp = fopen(filepath, "wb"); if((len = recv(sd, &fsize2, sizeof(fsize), 0)) < 0){ perror("recv"); exit(1); } fsize = ntohl(fsize2); i = 0; nsize = 0; printf("file size : %d\n", fsize); while(nsize < fsize){ //recv(sd, &fpsize2, sizeof(fpsize2), 0); //fpsize = ntohl(fpsize2); //printf("fpsize : %d\n", fpsize); if((len = recv(sd, buf, 4048, 0)) <= 0){ perror("recv"); exit(1); } nsize += len; printf("file size = %d, seq = %d, now_size = %d, recv_size = %d\n", fsize, i++, nsize, len); if(nsize <= fsize) fwrite(buf, 1, len, fp); else fwrite(buf, 1, len - sizeof(int), fp); } /*((char*)Q)[0] = buf[len-sizeof(int)]; ((char*)Q)[1] = buf[len-sizeof(int)+1]; ((char*)Q)[2] = buf[len-sizeof(int)+2]; ((char*)Q)[3] = buf[len-sizeof(int)+3];*/ memcpy((char*)&Q, &buf[len-4], sizeof(Q)); printf("Q is %d\n", Q); //printf("%d %d %d %d\n", buf[len-4], buf[len-3], buf[len-2], buf[len-1]); //printf("%d\n", Q); fclose(fp); //if(Q == endQ) break; //recv(sd, &Q, sizeof(Q), 0); //Q = ntohl(Q); //printf("%d\n", Q); //exit(1); /* if( (fid = open(filepath, O_CREAT | O_WRONLY | O_TRUNC, 0755)) < 0 ){ sprintf(log_buf, "file open fail : %s", filepath); logger(ERR, log_buf); exit(1); } i = 0; while(TRUE){ while((tlen = recv(sd, &len, sizeof(len), 0)) != sizeof(tlen)){ perror("recv"); //exit(1); } printf("%d %d %d\n", i++, len, ntohl(len)); tlen = ntohl(len); if(tlen == endQ) break; while((len = recv(sd, buf, tlen, 0)) != tlen){ printf("%d %d\n", len, tlen); perror("recv2"); exit(1); } if(write(fid, buf, len) < 0){ perror("write"); exit(1); } } i = 0; while(TRUE){ if(read(sd, &len, sizeof(len)) < 0){ perror("read"); exit(1); } printf("%d %d %d\n", i++, len, ntohl(len)); len = ntohl(len);// #if DEBUG //printf("len %d %d\n", len, endQ); #endif if(len == endQ) break; if((len = read(sd, buf, len)) < 0){ perror("read2"); exit(1); } if(write(fid, buf, len) < 0){ perror("write"); exit(1); } } if(fid) close(fid); sprintf(log_buf, "file[%s] is uploaded.", filepath); logger(SVR, log_buf);*/ } /* sprintf(log_buf, "Call: HTMLgen %s %s", user, date); logger(SVR, log_buf); sprintf(cmd, "./HTMLgen %s %s", user, date); #if DEBUG printf("%s\n", cmd); #endif system(cmd); sprintf(cmd, "./mail_sender %s %s %s", user, clientIP, date); system(cmd); sprintf(subject, "The backup of %s is finish.", user); sprintf(cmd, "mail -s \"$(echo -e \"%s\\nContent-Type: text/html\")\" %s < %s", subject, MAIL_RCPT, MAIL_PATH); system(cmd); }*/ } logger(SVR, "BACKUP REQUEST END"); if(sd) close(sd); exit(1); }
void master_service::proc_pre_jail(void) { logger(">>>proc_pre_jail<<<"); }
/** * Capture transmitted and received data ** * @author diego pessanha * @since 2009-02-01 * @desc get data info from pppd logs and stores in open3g logs **/ int trafego(){ char trbytes[101], tp1[10], tp2[10]; int tx, tx2, rx, rx2; //dados enviados FILE *pppstat= fopen("/sys/class/net/ppp0/statistics/tx_bytes","r"); if(pppstat==NULL){ printf("\033[2A"); printf("\033[K"); printf("Erro ao abrir arquivo log de dados."); logger("ERRO: Não foi possível abrir arquivo tx de log de dados do ppp. (coninfo.trafego)"); return 0; } fgets(trbytes, 101, pppstat); tx = atoi(trbytes); fclose(pppstat); pppstat = fopen("/etc/open3g/open3g_tx","r"); if(pppstat==NULL){ printf("\033[2A"); printf("\033[K"); printf("\nErro ao abrir arquivo log de dados.\n\n"); logger("ERRO: Não foi possível abrir arquivo tx de log de dados do discador. (coninfo.trafego)"); return 0; } fgets(trbytes, 101, pppstat); tx2 = atoi(trbytes); fclose(pppstat); tx2 = tx + tx2; FILE *txb2=fopen("/etc/open3g/open3g_tx","w"); fprintf(txb2,"%d",tx2); fclose(txb2); //dados recebidos pppstat = fopen("/sys/class/net/ppp0/statistics/rx_bytes","r"); if(pppstat==NULL){ printf("\033[2A"); printf("\033[K"); printf("\nErro ao abrir arquivo log de dados.\n\n"); logger("ERRO: Não foi possível abrir arquivo rx de log de dados do ppp. (coninfo.trafego)"); return 0; } fgets(trbytes,101,pppstat); rx = atoi(trbytes); fclose(pppstat); pppstat = fopen("/etc/open3g/open3g_rx","r"); if(pppstat==NULL){ printf("\033[2A"); printf("\033[K"); printf("\nErro ao abrir arquivo log de dados.\n\n"); logger("ERRO: Não foi possível abrir arquivo rx de log de dados do discador. (coninfo.trafego)"); return 0; } fgets(trbytes,101,pppstat); rx2 = atoi(trbytes); fclose(pppstat); rx2 = rx + rx2; txb2 = fopen("/etc/open3g/open3g_rx","w"); fprintf(txb2,"%d",rx2); fclose(txb2); //converte sprintf(tp1,"bytes"); sprintf(tp2,"bytes"); if (tx>1024){ tx=tx/1024; sprintf(tp1,"KB"); } if (tx>1024){ tx=tx/1024; sprintf(tp1,"MB"); } if (rx>1024){ rx=rx/1024; sprintf(tp2,"KB"); } if (rx>1024){ rx=rx/1024; sprintf(tp2,"MB"); } //Print data on screen printf("\033[2A"); //Move 2 lines up printf("\033[1A"); //Move 2 lines up printf("\033[K"); //Erase the line printf("Enviados: "); printf("%d %s",tx,tp1); printf(" | Recebidos: "); printf("%d %s\n\n",rx,tp2); char *args[] = {"get_signal","sig","-d","/dev/ttyUSB1"}; get_signal(4,args); return 0; }
static void setLog( assertFunction_Type log) { logger() = log; }