int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); if (parse_args (argc, argv) != 0) return 1; ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) - Acquiring Name Service\n"))); CORBA::Object_var nmobj = orb->resolve_initial_references ("NameManager"); FT_Naming::NamingManager_var naming_manager = FT_Naming::NamingManager::_narrow (nmobj.in()); TAO_Naming_Client name_svc; try { ACE_Time_Value timeout (10); // Wait up to 10 seconds for the naming service if (name_svc.init (orb.in (), &timeout) != 0) ACE_ERROR_RETURN ((LM_DEBUG, ACE_TEXT ("client: Could not connect to ") ACE_TEXT ("naming service.\n")), 1); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ( ACE_TEXT ("Exception caught while initializing name ") ACE_TEXT ("service facade:")); return 1; } Hammer hammer; if (hammer.setup(orb.in(), naming_manager.in()) == -1) { return 1; } CosNaming::Name name (1); name.length (1); name[0].id = CORBA::string_dup ("basic_name"); CORBA::Object_var tmp; Test::Basic_var basic; // Iterate enough so we get a few wrap-arounds for (int i = 0; i < 15; i++) { if (i == 3) { hammer.activate (THR_NEW_LWP | THR_JOINABLE, hammers); } try { // Each time we invoke resolve, we get a different member tmp = name_svc->resolve (name); // Narrow it to a Basic object basic = Test::Basic::_narrow (tmp.in ()); } catch (CORBA::Exception& ex) { ex._tao_print_exception (ACE_TEXT ("Error resolving name.\n")); } if (CORBA::is_nil (basic.in ())) { ACE_ERROR_RETURN ((LM_DEBUG, ACE_TEXT ("Server obj ref not obtained ") ACE_TEXT ("from Load Balancing Name Service\n"), ior), 1); } try { CORBA::String_var the_string = basic->get_string (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) - Client request handled ") ACE_TEXT ("by object at <%C>\n"), the_string.in ())); } catch (CORBA::Exception& ex) { ex._tao_print_exception ( ACE_TEXT ("Error invoking get_string on Basic object.\n")); return 1; } // Remove one member after we wrapped around to make sure naming manager can // handle it successufully if (i == 7) { try { // Try removing a member basic->remove_member (); } catch (CORBA::Exception& ex) { ex._tao_print_exception ( ACE_TEXT ("Error invoking get_string on Basic object.\n")); return 1; } } } hammer.wait (); try { basic->shutdown (); ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%P|%t) - Shutting down server\n"))); } catch (CORBA::Exception& ex) { ex._tao_print_exception ( ACE_TEXT ("Error invoking get_string on Basic object.\n")); return 1; } orb->destroy (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ( ACE_TEXT ("Exception caught in client.cpp:")); return 1; } return 0; }
int main(int argc, char *argv[]) { struct sigaction sact; cron_db database; setprogname(argv[0]); (void)setlocale(LC_ALL, ""); (void)setvbuf(stdout, NULL, _IOLBF, 0); (void)setvbuf(stderr, NULL, _IOLBF, 0); NoFork = 0; parse_args(argc, argv); (void)memset(&sact, 0, sizeof sact); (void)sigemptyset(&sact.sa_mask); sact.sa_flags = 0; #ifdef SA_RESTART sact.sa_flags |= SA_RESTART; #endif sact.sa_handler = sigchld_handler; (void) sigaction(SIGCHLD, &sact, NULL); sact.sa_handler = sighup_handler; (void) sigaction(SIGHUP, &sact, NULL); sact.sa_handler = quit; (void) sigaction(SIGINT, &sact, NULL); (void) sigaction(SIGTERM, &sact, NULL); acquire_daemonlock(0); set_cron_uid(); set_cron_cwd(); if (setenv("PATH", _PATH_DEFPATH, 1) < 0) { log_it("CRON", getpid(), "DEATH", "can't malloc"); exit(1); } /* if there are no debug flags turned on, fork as a daemon should. */ if (DebugFlags) { #if DEBUGGING (void)fprintf(stderr, "[%ld] cron started\n", (long)getpid()); #endif } else if (NoFork == 0) { if (daemon(1, 0)) { log_it("CRON",getpid(),"DEATH","can't fork"); exit(1); } } acquire_daemonlock(0); database.head = NULL; database.tail = NULL; database.mtime = (time_t) 0; load_database(&database); set_time(TRUE); run_reboot_jobs(&database); timeRunning = virtualTime = clockTime; /* * Too many clocks, not enough time (Al. Einstein) * These clocks are in minutes since the epoch, adjusted for timezone. * virtualTime: is the time it *would* be if we woke up * promptly and nobody ever changed the clock. It is * monotonically increasing... unless a timejump happens. * At the top of the loop, all jobs for 'virtualTime' have run. * timeRunning: is the time we last awakened. * clockTime: is the time when set_time was last called. */ for (;;) { time_t timeDiff; enum timejump wakeupKind; /* ... wait for the time (in minutes) to change ... */ do { cron_sleep(timeRunning + 1); set_time(FALSE); } while (clockTime == timeRunning); timeRunning = clockTime; /* * Calculate how the current time differs from our virtual * clock. Classify the change into one of 4 cases. */ timeDiff = timeRunning - virtualTime; /* shortcut for the most common case */ if (timeDiff == 1) { virtualTime = timeRunning; find_jobs(virtualTime, &database, TRUE, TRUE); } else { if (timeDiff > (3*MINUTE_COUNT) || timeDiff < -(3*MINUTE_COUNT)) wakeupKind = large; else if (timeDiff > 5) wakeupKind = medium; else if (timeDiff > 0) wakeupKind = small; else wakeupKind = negative; switch (wakeupKind) { case small: /* * case 1: timeDiff is a small positive number * (wokeup late) run jobs for each virtual * minute until caught up. */ Debug(DSCH, ("[%jd], normal case %jd minutes to go\n", (intmax_t)getpid(), (intmax_t)timeDiff)); do { if (job_runqueue()) (void)sleep(10); virtualTime++; find_jobs(virtualTime, &database, TRUE, TRUE); } while (virtualTime < timeRunning); break; case medium: /* * case 2: timeDiff is a medium-sized positive * number, for example because we went to DST * run wildcard jobs once, then run any * fixed-time jobs that would otherwise be * skipped if we use up our minute (possible, * if there are a lot of jobs to run) go * around the loop again so that wildcard jobs * have a chance to run, and we do our * housekeeping. */ Debug(DSCH, ("[%jd], DST begins %jd minutes to go\n", (intmax_t)getpid(), (intmax_t)timeDiff)); /* run wildcard jobs for current minute */ find_jobs(timeRunning, &database, TRUE, FALSE); /* run fixed-time jobs for each minute missed */ do { if (job_runqueue()) (void)sleep(10); virtualTime++; find_jobs(virtualTime, &database, FALSE, TRUE); set_time(FALSE); } while (virtualTime < timeRunning && clockTime == timeRunning); break; case negative: /* * case 3: timeDiff is a small or medium-sized * negative num, eg. because of DST ending. * Just run the wildcard jobs. The fixed-time * jobs probably have already run, and should * not be repeated. Virtual time does not * change until we are caught up. */ Debug(DSCH, ("[%jd], DST ends %jd minutes to go\n", (intmax_t)getpid(), (intmax_t)timeDiff)); find_jobs(timeRunning, &database, TRUE, FALSE); break; default: /* * other: time has changed a *lot*, * jump virtual time, and run everything */ Debug(DSCH, ("[%ld], clock jumped\n", (long)getpid())); virtualTime = timeRunning; find_jobs(timeRunning, &database, TRUE, TRUE); } } /* Jobs to be run (if any) are loaded; clear the queue. */ (void)job_runqueue(); /* Check to see if we received a signal while running jobs. */ if (got_sighup) { got_sighup = 0; log_close(); } if (got_sigchld) { got_sigchld = 0; sigchld_reaper(); } load_database(&database); } }
asmlinkage void __init start_kernel(void) { char * command_line; extern struct kernel_param __start___param[], __stop___param[]; smp_setup_processor_id(); /* * Need to run as early as possible, to initialize the * lockdep hash: */ unwind_init(); lockdep_init(); cgroup_init_early(); local_irq_disable(); early_boot_irqs_off(); early_init_irq_lock_class(); /* * Interrupts are still disabled. Do necessary setups, then * enable them */ lock_kernel(); tick_init(); boot_cpu_init(); page_address_init(); printk(KERN_NOTICE); printk(linux_banner); setup_arch(&command_line); setup_command_line(command_line); unwind_setup(); setup_per_cpu_areas(); smp_prepare_boot_cpu(); /* arch-specific boot-cpu hooks */ /* * Set up the scheduler prior starting any interrupts (such as the * timer interrupt). Full topology setup happens at smp_init() * time - but meanwhile we still have a functioning scheduler. */ sched_init(); /* * Disable preemption - early bootup scheduling is extremely * fragile until we cpu_idle() for the first time. */ preempt_disable(); build_all_zonelists(); page_alloc_init(); printk(KERN_NOTICE "Kernel command line: %s\n", boot_command_line); parse_early_param(); parse_args("Booting kernel", static_command_line, __start___param, __stop___param - __start___param, &unknown_bootoption); if (!irqs_disabled()) { printk(KERN_WARNING "start_kernel(): bug: interrupts were " "enabled *very* early, fixing it\n"); local_irq_disable(); } sort_main_extable(); trap_init(); rcu_init(); init_IRQ(); pidhash_init(); init_timers(); hrtimers_init(); softirq_init(); timekeeping_init(); time_init(); profile_init(); if (!irqs_disabled()) printk("start_kernel(): bug: interrupts were enabled early\n"); early_boot_irqs_on(); local_irq_enable(); /* * HACK ALERT! This is early. We're enabling the console before * we've done PCI setups etc, and console_init() must be aware of * this. But we do want output early, in case something goes wrong. */ console_init(); if (panic_later) panic(panic_later, panic_param); lockdep_info(); /* * Need to run this when irqs are enabled, because it wants * to self-test [hard/soft]-irqs on/off lock inversion bugs * too: */ locking_selftest(); #ifdef CONFIG_BLK_DEV_INITRD if (initrd_start && !initrd_below_start_ok && initrd_start < min_low_pfn << PAGE_SHIFT) { printk(KERN_CRIT "initrd overwritten (0x%08lx < 0x%08lx) - " "disabling it.\n",initrd_start,min_low_pfn << PAGE_SHIFT); initrd_start = 0; } #endif vfs_caches_init_early(); cpuset_init_early(); mem_init(); enable_debug_pagealloc(); cpu_hotplug_init(); kmem_cache_init(); setup_per_cpu_pageset(); numa_policy_init(); if (late_time_init) late_time_init(); calibrate_delay(); pidmap_init(); pgtable_cache_init(); prio_tree_init(); anon_vma_init(); #ifdef CONFIG_X86 if (efi_enabled) efi_enter_virtual_mode(); #endif fork_init(num_physpages); proc_caches_init(); buffer_init(); unnamed_dev_init(); key_init(); security_init(); vfs_caches_init(num_physpages); radix_tree_init(); signals_init(); /* rootfs populating might need page-writeback */ page_writeback_init(); #ifdef CONFIG_PROC_FS proc_root_init(); #endif cgroup_init(); cpuset_init(); taskstats_init_early(); delayacct_init(); check_bugs(); acpi_early_init(); /* before LAPIC and SMP init */ /* Do the rest non-__init'ed, we're now alive */ rest_init(); }
static void cmd_write_value(struct client *cli, char *cmd_str) { int opt, i, val; char *argvbuf[516]; char **argv = argvbuf; int argc = 1; uint16_t handle; char *endptr = NULL; int length; uint8_t *value = NULL; bool without_response = false; bool signed_write = false; if (!bt_gatt_client_is_ready(cli->gatt)) { printf("GATT client not initialized\n"); return; } if (!parse_args(cmd_str, 514, argv + 1, &argc)) { printf("Too many arguments\n"); write_value_usage(); return; } optind = 0; argv[0] = "write-value"; while ((opt = getopt_long(argc, argv, "+ws", write_value_options, NULL)) != -1) { switch (opt) { case 'w': without_response = true; break; case 's': signed_write = true; break; default: write_value_usage(); return; } } argc -= optind; argv += optind; if (argc < 1) { write_value_usage(); return; } handle = strtol(argv[0], &endptr, 0); if (!endptr || *endptr != '\0' || !handle) { printf("Invalid handle: %s\n", argv[0]); return; } length = argc - 1; if (length > 0) { if (length > UINT16_MAX) { printf("Write value too long\n"); return; } value = malloc(length); if (!value) { printf("Failed to construct write value\n"); return; } for (i = 1; i < argc; i++) { val = strtol(argv[i], &endptr, 0); if (endptr == argv[i] || *endptr != '\0' || errno == ERANGE || val < 0 || val > 255) { printf("Invalid value byte: %s\n", argv[i]); goto done; } value[i-1] = val; } } if (without_response) { if (!bt_gatt_client_write_without_response(cli->gatt, handle, signed_write, value, length)) { printf("Failed to initiate write without response " "procedure\n"); goto done; } printf("Write command sent\n"); goto done; } if (!bt_gatt_client_write_value(cli->gatt, handle, value, length, write_cb, NULL, NULL)) printf("Failed to initiate write procedure\n"); done: free(value); }
static void cmd_write_prepare(struct client *cli, char *cmd_str) { int opt, i, val; char *argvbuf[516]; char **argv = argvbuf; int argc = 0; unsigned int id = 0; uint16_t handle; uint16_t offset; char *endptr = NULL; unsigned int length; uint8_t *value = NULL; if (!bt_gatt_client_is_ready(cli->gatt)) { printf("GATT client not initialized\n"); return; } if (!parse_args(cmd_str, 514, argv + 1, &argc)) { printf("Too many arguments\n"); write_value_usage(); return; } /* Add command name for getopt_long */ argc++; argv[0] = "write-prepare"; optind = 0; while ((opt = getopt_long(argc, argv , "s:", write_prepare_options, NULL)) != -1) { switch (opt) { case 's': if (!optarg) { write_prepare_usage(); return; } id = atoi(optarg); break; default: write_prepare_usage(); return; } } argc -= optind; argv += optind; if (argc < 3) { write_prepare_usage(); return; } if (cli->reliable_session_id != id) { printf("Session id != Ongoing session id (%u!=%u)\n", id, cli->reliable_session_id); return; } handle = strtol(argv[0], &endptr, 0); if (!endptr || *endptr != '\0' || !handle) { printf("Invalid handle: %s\n", argv[0]); return; } endptr = NULL; offset = strtol(argv[1], &endptr, 0); if (!endptr || *endptr != '\0' || errno == ERANGE) { printf("Invalid offset: %s\n", argv[1]); return; } /* * First two arguments are handle and offset. What remains is the value * length */ length = argc - 2; if (length == 0) goto done; if (length > UINT16_MAX) { printf("Write value too long\n"); return; } value = malloc(length); if (!value) { printf("Failed to allocate memory for value\n"); return; } for (i = 2; i < argc; i++) { val = strtol(argv[i], &endptr, 0); if (endptr == argv[i] || *endptr != '\0' || errno == ERANGE || val < 0 || val > 255) { printf("Invalid value byte: %s\n", argv[i]); free(value); return; } value[i-2] = val; } done: cli->reliable_session_id = bt_gatt_client_prepare_write(cli->gatt, id, handle, offset, value, length, write_long_cb, NULL, NULL); if (!cli->reliable_session_id) printf("Failed to proceed prepare write\n"); else printf("Prepare write success.\n" "Session id: %d to be used on next write\n", cli->reliable_session_id); free(value); }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); CORBA::Object_var poa_object = orb->resolve_initial_references("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); if (CORBA::is_nil (root_poa.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Panic: nil RootPOA\n"), 1); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); // Make all oneways "reliable." { CORBA::Object_var manager_object = orb->resolve_initial_references("ORBPolicyManager"); CORBA::PolicyManager_var policy_manager = CORBA::PolicyManager::_narrow(manager_object.in()); if (CORBA::is_nil (policy_manager.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Panic: nil PolicyManager\n"), 1); CORBA::Any policy_value; policy_value <<= Messaging::SYNC_WITH_SERVER; CORBA::PolicyList policies(1); policies.length(1); policies[0] = orb->create_policy (Messaging::SYNC_SCOPE_POLICY_TYPE, policy_value); policy_manager->set_policy_overrides (policies, CORBA::ADD_OVERRIDE); policies[0]->destroy (); } if (parse_args (argc, argv) != 0) return 1; CORBA::Object_var tmp = orb->string_to_object(ior); Test::Service_var service = Test::Service::_narrow(tmp.in ()); if (CORBA::is_nil (service.in ())) { ACE_ERROR_RETURN ((LM_DEBUG, "Nil service reference <%s>\n", ior), 1); } Callback *callback_impl; ACE_NEW_RETURN (callback_impl, Callback(orb.in ()), 1); PortableServer::ServantBase_var owner_transfer(callback_impl); PortableServer::ObjectId_var id = root_poa->activate_object (callback_impl); CORBA::Object_var object = root_poa->id_to_reference (id.in ()); Test::Callback_var callback = Test::Callback::_narrow (object.in ()); poa_manager->activate (); ACE_DEBUG ((LM_DEBUG, "(%P|%t) client - starting test\n")); service->run_test (callback.in ()); ACE_DEBUG ((LM_DEBUG, "(%P|%t) client - running ORB\n")); orb->run (); root_poa->destroy (1, 1); orb->destroy (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); return 1; } return 0; }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { if (parse_args (argc, argv) == -1) return -1; try { ACE_Argv_Type_Converter satc (argc, argv); CORBA::ORB_var sorb = CORBA::ORB_init (satc.get_argc (), satc.get_TCHAR_argv (), server_orb.c_str ()); ACE_Manual_Event me; Server_Task server_task (output, simple_test_output, sorb.in (), me, ACE_Thread_Manager::instance ()); if (server_task.activate (THR_NEW_LWP | THR_JOINABLE, 1, 1) == -1) { ACE_ERROR ((LM_ERROR, "Error activating server task\n")); } // Wait for the server thread to do some processing me.wait (); ACE_Argv_Type_Converter catc (argc, argv); CORBA::ORB_var corb = CORBA::ORB_init (catc.get_argc (), catc.get_TCHAR_argv (), client_orb.c_str ()); Client_Task client_task (input, simple_test_input, corb.in (), ACE_Thread_Manager::instance ()); if (client_task.activate (THR_NEW_LWP | THR_JOINABLE, 1, 1) == -1) { ACE_ERROR ((LM_ERROR, "Error activating client task\n")); } // Wait for the client and server to finish ACE_Thread_Manager::instance ()->wait (); // Now that all threads have completed we can destroy the ORB sorb->destroy (); if (server_orb != client_orb) { corb->destroy (); } CORBA::ULong errors = client_task.error_count () + server_task.error_count (); if (errors == 0) { ACE_DEBUG((LM_DEBUG, "(%P|%t) test passed\n")); } else { ACE_DEBUG((LM_DEBUG, "(%P|%t) test failed - error_count=%u\n", errors)); return 1; } } catch (const CORBA::Exception&) { // Ignore exceptions.. } return 0; }
static int accept_liveupgrade_single(cJSON *client, int *rxerr_map, int rxerr_map_len) { cJSON *fd, *listener_id, *username, *time_connect, *tick_connect; cJSON *state; cJSON *addr_loc; cJSON *udp_port; cJSON *app_name, *app_version; cJSON *verified; cJSON *obuf_q; cJSON *bytes_rx, *bytes_tx; cJSON *pkts_rx, *pkts_tx, *pkts_ign; cJSON *rx_errs; cJSON *filter; cJSON *ibuf, *obuf; cJSON *client_heard; cJSON *lat, *lng; unsigned addr_len; union sockaddr_u sa; char *argv[256]; int i, argc; const char *username_s = "unknown"; /* get username first, so we can log it later */ username = accept_liveupgrade_cJSON_get(client, "username", cJSON_String, username_s); if (username) username_s = username->valuestring; fd = accept_liveupgrade_cJSON_get(client, "fd", cJSON_Number, username_s); int fd_i = -1; if (fd) fd_i = fd->valueint; if (fd_i < 0) { hlog(LOG_INFO, "Live upgrade: Client '%s' has negative fd %d, ignoring (corepeer?)", username_s, fd_i); return -1; } listener_id = accept_liveupgrade_cJSON_get(client, "listener_id", cJSON_Number, username_s); state = accept_liveupgrade_cJSON_get(client, "state", cJSON_String, username_s); time_connect = accept_liveupgrade_cJSON_get(client, "t_connect", cJSON_Number, username_s); addr_loc = accept_liveupgrade_cJSON_get(client, "addr_loc", cJSON_String, username_s); app_name = accept_liveupgrade_cJSON_get(client, "app_name", cJSON_String, username_s); app_version = accept_liveupgrade_cJSON_get(client, "app_version", cJSON_String, username_s); verified = accept_liveupgrade_cJSON_get(client, "verified", cJSON_Number, username_s); obuf_q = accept_liveupgrade_cJSON_get(client, "obuf_q", cJSON_Number, username_s); bytes_rx = accept_liveupgrade_cJSON_get(client, "bytes_rx", cJSON_Number, username_s); bytes_tx = accept_liveupgrade_cJSON_get(client, "bytes_tx", cJSON_Number, username_s); pkts_rx = accept_liveupgrade_cJSON_get(client, "pkts_rx", cJSON_Number, username_s); pkts_tx = accept_liveupgrade_cJSON_get(client, "pkts_tx", cJSON_Number, username_s); pkts_ign = accept_liveupgrade_cJSON_get(client, "pkts_ign", cJSON_Number, username_s); rx_errs = accept_liveupgrade_cJSON_get(client, "rx_errs", cJSON_Array, username_s); filter = accept_liveupgrade_cJSON_get(client, "filter", cJSON_String, username_s); /* optional */ tick_connect = cJSON_GetObjectItem(client, "t_connect_tick"); udp_port = cJSON_GetObjectItem(client, "udp_port"); ibuf = cJSON_GetObjectItem(client, "ibuf"); obuf = cJSON_GetObjectItem(client, "obuf"); client_heard = cJSON_GetObjectItem(client, "client_heard"); lat = cJSON_GetObjectItem(client, "lat"); lng = cJSON_GetObjectItem(client, "lng"); if (!( (fd) && (listener_id) && (state) && (username) && (time_connect) && (addr_loc) && (app_name) && (app_version) && (verified) && (obuf_q) && (bytes_rx) && (bytes_tx) && (pkts_rx) && (pkts_tx) && (pkts_ign) && (rx_errs) && (filter) )) { hlog(LOG_ERR, "Live upgrade: Fields missing from client JSON, discarding client fd %d", fd_i); if (fd_i >= 0) close(fd_i); return -1; } hlog(LOG_DEBUG, "Old client on fd %d: %s", fd->valueint, username->valuestring); /* fetch peer address from the fd instead of parsing it from text */ addr_len = sizeof(sa); if (getpeername(fd->valueint, &sa.sa, &addr_len) != 0) { /* Sometimes clients disconnect during upgrade, especially on slow RPi servers... */ if (errno == ENOTCONN) hlog(LOG_INFO, "Live upgrade: Client %s on fd %d has disconnected during upgrade (%s)", username->valuestring, fd->valueint, strerror(errno)); else hlog(LOG_ERR, "Live upgrade: getpeername client fd %d failed: %s", fd->valueint, strerror(errno)); close(fd->valueint); return -1; } /* convert client address to string */ char *client_addr_s = strsockaddr( &sa.sa, addr_len ); /* find the right listener for this client, for configuration and accounting */ struct listen_t *l = liveupgrade_find_listener(listener_id->valueint); if (!l) { hlog(LOG_INFO, "Live upgrade: Listener has been removed for fd %d (%s - local %s): disconnecting %s", fd->valueint, client_addr_s, addr_loc->valuestring, username->valuestring); close(fd->valueint); hfree(client_addr_s); return -1; } struct client_t *c = accept_client_for_listener(l, fd->valueint, client_addr_s, &sa, addr_len); if (!c) { hlog(LOG_ERR, "Live upgrade - client_alloc returned NULL, too many clients. Denied client %s on fd %d from %s", username->valuestring, fd->valueint, client_addr_s); close(fd->valueint); hfree(client_addr_s); return -1; } hfree(client_addr_s); if (strcmp(state->valuestring, "connected") == 0) { c->state = CSTATE_CONNECTED; c->handler_line_in = &incoming_handler; strncpy(c->username, username->valuestring, sizeof(c->username)); c->username[sizeof(c->username)-1] = 0; c->username_len = strlen(c->username); } else if (strcmp(state->valuestring, "login") == 0) { c->state = CSTATE_LOGIN; c->handler_line_in = &login_handler; } else { hlog(LOG_ERR, "Live upgrade: Client %s is in invalid state '%s' (fd %d)", l->addr_s, state->valuestring, l->fd); goto err; } /* distribute keepalive intervals for the existing old clients * but send them rather sooner than later */ // coverity[dont_call] // squelch warning: not security sensitive use of random(): load distribution c->keepalive = tick + (random() % (keepalive_interval/2)); /* distribute cleanup intervals over the next 2 minutes */ // coverity[dont_call] // squelch warning: not security sensitive use of random(): load distribution c->cleanup = tick + (random() % 120); c->connect_time = time_connect->valueint; /* live upgrade / backward compatibility: upgrading from <= 1.8.2 requires the 'else' path' */ if (tick_connect && tick_connect->type == cJSON_Number) c->connect_tick = tick_connect->valueint; else /* convert to monotonic time */ c->connect_tick = tick - (now - c->connect_time); c->validated = verified->valueint; c->localaccount.rxbytes = bytes_rx->valuedouble; c->localaccount.txbytes = bytes_tx->valuedouble; c->localaccount.rxpackets = pkts_rx->valuedouble; c->localaccount.txpackets = pkts_tx->valuedouble; c->localaccount.rxdrops = pkts_ign->valuedouble; login_set_app_name(c, app_name->valuestring, app_version->valuestring); // handle client's filter setting if (c->flags & CLFLAGS_USERFILTEROK && (filter) && (filter->valuestring) && *(filter->valuestring)) { // archive a copy of the filters, for status display strncpy(c->filter_s, filter->valuestring, FILTER_S_SIZE); c->filter_s[FILTER_S_SIZE-1] = 0; sanitize_ascii_string(c->filter_s); char *f = hstrdup(filter->valuestring); argc = parse_args(argv, f); for (i = 0; i < argc; ++i) { filter_parse(c, argv[i], 1); } hfree(f); } // set up UDP downstream if necessary if (udp_port && udp_port->type == cJSON_Number && udp_port->valueint > 1024 && udp_port->valueint < 65536) { if (login_setup_udp_feed(c, udp_port->valueint) != 0) { hlog(LOG_DEBUG, "%s/%s: Requested UDP on client port with no UDP configured", c->addr_rem, c->username); } } // fill up ibuf if (ibuf && ibuf->type == cJSON_String && ibuf->valuestring) { int l = hex_decode(c->ibuf, c->ibuf_size, ibuf->valuestring); if (l < 0) { hlog(LOG_ERR, "Live upgrade: %s/%s: Failed to decode ibuf: %s", c->addr_rem, c->username, ibuf->valuestring); } else { c->ibuf_end = l; hlog(LOG_DEBUG, "Live upgrade: Decoded ibuf %d bytes: '%.*s'", l, l, c->ibuf); hlog(LOG_DEBUG, "Hex: %s", ibuf->valuestring); } } // fill up obuf if (obuf && obuf->type == cJSON_String && obuf->valuestring) { int l = hex_decode(c->obuf, c->obuf_size, obuf->valuestring); if (l < 0) { hlog(LOG_ERR, "Live upgrade: %s/%s: Failed to decode obuf: %s", c->addr_rem, c->username, obuf->valuestring); } else { c->obuf_start = 0; c->obuf_end = l; hlog(LOG_DEBUG, "Live upgrade: Decoded obuf %d bytes: '%.*s'", l, l, c->obuf); hlog(LOG_DEBUG, "Hex: %s", obuf->valuestring); } } /* load list of stations heard by this client, to immediately support * messaging */ if (client_heard && client_heard->type == cJSON_Array) client_heard_json_load(c, client_heard); /* load rxerrs counters, with error name string mapping to support * adding/reordering of error counters */ if (rx_errs && rx_errs->type == cJSON_Array && rxerr_map && rxerr_map_len > 0) accept_rx_err_load(c, rx_errs, rxerr_map, rxerr_map_len); /* set client lat/lon, if they're given */ if (lat && lng && lat->type == cJSON_Number && lng->type == cJSON_Number) { c->loc_known = 1; c->lat = lat->valuedouble; c->lng = lng->valuedouble; } hlog(LOG_DEBUG, "%s - Accepted live upgrade client on fd %d from %s", c->addr_loc, c->fd, c->addr_rem); /* set client socket options, return -1 on serious errors */ if (set_client_sockopt(c) != 0) goto err; /* Add the client to the client list. */ int old_fd = clientlist_add(c); if (c->validated && old_fd != -1) { /* TODO: If old connection is SSL validated, and this one is not, do not disconnect it. */ hlog(LOG_INFO, "fd %d: Disconnecting duplicate validated client with username '%s'", old_fd, c->username); shutdown(old_fd, SHUT_RDWR); } /* ok, found it... lock the new client queue and pass the client */ if (pass_client_to_worker(pick_next_worker(), c)) goto err; return 0; err: close(c->fd); inbound_connects_account(0, c->portaccount); /* something failed, remove this from accounts.. */ client_free(c); return -1; }
void __init parse_early_options(char *cmdline) { parse_args("early options", cmdline, NULL, 0, do_early_param); }
int main(int argc, char **argv) { int rc; struct worker_thread *worker; rc = parse_args(argc, argv); if (rc != 0) { return rc; } ealargs[1] = sprintf_alloc("-c %s", g_core_mask ? g_core_mask : "0x1"); rc = rte_eal_init(sizeof(ealargs) / sizeof(ealargs[0]), ealargs); free(ealargs[1]); if (rc < 0) { fprintf(stderr, "could not initialize dpdk\n"); return 1; } request_mempool = rte_mempool_create("nvme_request", 8192, nvme_request_size(), 128, 0, NULL, NULL, NULL, NULL, SOCKET_ID_ANY, 0); if (request_mempool == NULL) { fprintf(stderr, "could not initialize request mempool\n"); return 1; } task_pool = rte_mempool_create("task_pool", 2048, sizeof(struct perf_task), 64, 0, NULL, NULL, task_ctor, NULL, SOCKET_ID_ANY, 0); g_tsc_rate = rte_get_timer_hz(); register_workers(); register_controllers(); /* Launch all of the slave workers */ worker = g_workers->next; while (worker != NULL) { if (worker->namespaces != NULL) { rte_eal_remote_launch(work_fn, worker, worker->lcore); } worker = worker->next; } work_fn(g_workers); worker = g_workers->next; while (worker != NULL) { if (worker->namespaces != NULL) { if (rte_eal_wait_lcore(worker->lcore) < 0) { return -1; } } worker = worker->next; } print_stats(); unregister_controllers(); return 0; }
int main (int argc, char **argv) { unsigned int count = 0; parse_args(argc, argv); if (!endpoint || !name) { zsys_error("endpoint or name not specified."); usage(); } mlm_client_t *client = mlm_client_new (); assert(client); int rv; rv = mlm_client_connect(client, endpoint, 5000, name); if (rv == -1) { zsys_error("connection failed."); mlm_client_destroy (&client); return -1; } rv = mlm_client_set_producer (client, "stream"); if (rv == -1) { zsys_error("set_producer failed."); mlm_client_destroy (&client); return -2; } zsock_t *pipe = mlm_client_msgpipe (client); if (!pipe) { zsys_error ("mlm_client_msgpipe() failed."); mlm_client_destroy (&client); return -3; } zpoller_t *poller = zpoller_new (pipe, NULL); if (!poller) { zsys_error("zpoller_new() failed."); mlm_client_destroy (&client); return -4; } while ( !zsys_interrupted && ( !num_messages || count < num_messages) ) { zsock_t *which = zpoller_wait (poller, interval); if ( which != NULL ) { // so we have something to receive zmsg_t *recv_msg = mlm_client_recv (client); zmsg_destroy (&recv_msg); } // in any case we are going to send something // zclock_sleep(interval); zmsg_t *msg = zmsg_new(); assert (msg); if ( count % 10 == 0) { zmsg_pushstr (msg, "exit"); } else { zmsg_pushstr (msg, "hello"); } zmsg_print(msg); mlm_client_send (client, "testing message", &msg); zmsg_destroy (&msg); ++count; } mlm_client_destroy(&client); zpoller_destroy(&poller); free(endpoint); free(name); zsys_info ("finished, sent: %u.", count); return 0; }
int main(int argc, char* argv[]) { parse_args(argc, argv); return argc; }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc,argv); CORBA::Object_var poa_object = orb->resolve_initial_references ("RootPOA"); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); if (parse_args (argc, argv) != 0) return -1; { test_factory_i *servant = new test_factory_i (orb.in ()); PortableServer::ServantBase_var safe_servant (servant); ACE_UNUSED_ARG (safe_servant); PortableServer::ObjectId_var id_act = root_poa->activate_object (servant); CORBA::Object_var object = root_poa->id_to_reference (id_act.in ()); test_factory_var test_factory = test_factory::_narrow (object.in ()); CORBA::String_var ior = orb->object_to_string (test_factory.in ()); FILE *output_file = ACE_OS::fopen (ior_output_file, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", ior_output_file), -1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); } poa_manager->activate (); TAO_Root_POA *tao_poa = dynamic_cast <TAO_Root_POA*> (root_poa.in ()); while (!done) { CORBA::ULong outstanding_requests = tao_poa->outstanding_requests (); ACE_DEBUG ((LM_DEBUG, "Number of outstanding requests before ORB::perform_work(): %d\n", outstanding_requests)); ACE_ASSERT (outstanding_requests == 0); orb->perform_work (); // On some systems this loop must yield or else the other threads // will not get a chance to run. ACE_OS::thr_yield (); } } catch (...) { ACE_ERROR_RETURN ((LM_ERROR, "Failure: Unexpected exception caught\n"), -1); } return 0; }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); if (parse_args (argc, argv) != 0) return 1; Worker worker (orb.in ()); if (worker.activate (THR_NEW_LWP | THR_JOINABLE, nthreads) != 0) ACE_ERROR_RETURN ((LM_ERROR, "(%P|%t) Cannot activate worker threads\n"), 1); int timeout = 30; int now = 0; while (now < timeout && worker.got_object_not_exist () != expected_object_not_exist) { now += 5; ACE_Time_Value tv (5, 0); orb->run (tv); } if (do_shutdown) { CORBA::Object_var object = orb->string_to_object (ior); Simple_Server_var server = Simple_Server::_narrow (object.in ()); server->shutdown (); } orb->shutdown (); worker.thr_mgr ()->wait (); orb->destroy (); if (worker.got_object_not_exist () != expected_object_not_exist) { ACE_ERROR_RETURN ((LM_ERROR, "(%P|%t)client: test failed.\n"), 1); } else { ACE_DEBUG ((LM_DEBUG, "(%P|%t)client: test passed.\n")); } } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught in main:"); return 1; } return 0; }
int cmd_reset(int argc, const char **argv, const char *prefix) { int reset_type = NONE, update_ref_status = 0, quiet = 0; int patch_mode = 0, unborn; const char *rev; unsigned char sha1[20]; const char **pathspec = NULL; const struct option options[] = { OPT__QUIET(&quiet, N_("be quiet, only report errors")), OPT_SET_INT(0, "mixed", &reset_type, N_("reset HEAD and index"), MIXED), OPT_SET_INT(0, "soft", &reset_type, N_("reset only HEAD"), SOFT), OPT_SET_INT(0, "hard", &reset_type, N_("reset HEAD, index and working tree"), HARD), OPT_SET_INT(0, "merge", &reset_type, N_("reset HEAD, index and working tree"), MERGE), OPT_SET_INT(0, "keep", &reset_type, N_("reset HEAD but keep local changes"), KEEP), OPT_BOOLEAN('p', "patch", &patch_mode, N_("select hunks interactively")), OPT_END() }; git_config(git_default_config, NULL); argc = parse_options(argc, argv, prefix, options, git_reset_usage, PARSE_OPT_KEEP_DASHDASH); pathspec = parse_args(argv, prefix, &rev); unborn = !strcmp(rev, "HEAD") && get_sha1("HEAD", sha1); if (unborn) { /* reset on unborn branch: treat as reset to empty tree */ hashcpy(sha1, EMPTY_TREE_SHA1_BIN); } else if (!pathspec) { struct commit *commit; if (get_sha1_committish(rev, sha1)) die(_("Failed to resolve '%s' as a valid revision."), rev); commit = lookup_commit_reference(sha1); if (!commit) die(_("Could not parse object '%s'."), rev); hashcpy(sha1, commit->object.sha1); } else { struct tree *tree; if (get_sha1_treeish(rev, sha1)) die(_("Failed to resolve '%s' as a valid tree."), rev); tree = parse_tree_indirect(sha1); if (!tree) die(_("Could not parse object '%s'."), rev); hashcpy(sha1, tree->object.sha1); } if (patch_mode) { if (reset_type != NONE) die(_("--patch is incompatible with --{hard,mixed,soft}")); return run_add_interactive(sha1_to_hex(sha1), "--patch=reset", pathspec); } /* git reset tree [--] paths... can be used to * load chosen paths from the tree into the index without * affecting the working tree nor HEAD. */ if (pathspec) { if (reset_type == MIXED) warning(_("--mixed with paths is deprecated; use 'git reset -- <paths>' instead.")); else if (reset_type != NONE) die(_("Cannot do %s reset with paths."), _(reset_type_names[reset_type])); } if (reset_type == NONE) reset_type = MIXED; /* by default */ if (reset_type != SOFT && reset_type != MIXED) setup_work_tree(); if (reset_type == MIXED && is_bare_repository()) die(_("%s reset is not allowed in a bare repository"), _(reset_type_names[reset_type])); /* Soft reset does not touch the index file nor the working tree * at all, but requires them in a good order. Other resets reset * the index file to the tree object we are switching to. */ if (reset_type == SOFT || reset_type == KEEP) die_if_unmerged_cache(reset_type); if (reset_type != SOFT) { struct lock_file *lock = xcalloc(1, sizeof(struct lock_file)); int newfd = hold_locked_index(lock, 1); if (reset_type == MIXED) { if (read_from_tree(pathspec, sha1)) return 1; } else { int err = reset_index(sha1, reset_type, quiet); if (reset_type == KEEP && !err) err = reset_index(sha1, MIXED, quiet); if (err) die(_("Could not reset index file to revision '%s'."), rev); } if (reset_type == MIXED) { /* Report what has not been updated. */ int flags = quiet ? REFRESH_QUIET : REFRESH_IN_PORCELAIN; refresh_index(&the_index, flags, NULL, NULL, _("Unstaged changes after reset:")); } if (write_cache(newfd, active_cache, active_nr) || commit_locked_index(lock)) die(_("Could not write new index file.")); } if (!pathspec && !unborn) { /* Any resets without paths update HEAD to the head being * switched to, saving the previous head in ORIG_HEAD before. */ update_ref_status = update_refs(rev, sha1); if (reset_type == HARD && !update_ref_status && !quiet) print_new_head_line(lookup_commit_reference(sha1)); } if (!pathspec) remove_branch_state(); return update_ref_status; }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); CORBA::Object_var poa_object = orb->resolve_initial_references("RootPOA"); if (CORBA::is_nil (poa_object.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Unable to initialize the POA.\n"), 1); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); if (parse_args (argc, argv) != 0) return 1; Manager manager_impl (orb.in ()); PortableServer::ObjectId_var id = root_poa->activate_object (&manager_impl); CORBA::Object_var object = root_poa->id_to_reference (id.in ()); Test::Manager_var manager = Test::Manager::_narrow (object.in ()); CORBA::String_var ior = orb->object_to_string (manager.in ()); // If the ior_output_file exists, output the ior to it FILE *output_file= ACE_OS::fopen (ior_output_file, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", ior_output_file), 1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); poa_manager->activate (); orb->run (); // ACE_DEBUG ((LM_DEBUG, "event loop finished\n")); root_poa->destroy (1, 1); orb->destroy (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); return 1; } return 0; }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { int status = 0; try { ACE_DEBUG((LM_INFO,"(%P|%t) %T publisher main\n")); ::DDS::DomainParticipantFactory_var dpf = TheParticipantFactoryWithArgs(argc, argv); // let the Service_Participant (in above line) strip out -DCPSxxx parameters // and then get application specific parameters. parse_args (argc, argv); ::Xyz::FooTypeSupport_var fts(new ::Xyz::FooTypeSupportImpl); ::DDS::DomainParticipant_var dp = dpf->create_participant(MY_DOMAIN, PARTICIPANT_QOS_DEFAULT, ::DDS::DomainParticipantListener::_nil(), ::OpenDDS::DCPS::DEFAULT_STATUS_MASK); if (CORBA::is_nil (dp.in ())) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) create_participant failed.\n"))); return 1 ; } if (::DDS::RETCODE_OK != fts->register_type(dp.in (), MY_TYPE)) { ACE_ERROR ((LM_ERROR, ACE_TEXT ("Failed to register the FooTypeSupport."))); return 1; } ::DDS::TopicQos topic_qos; dp->get_default_topic_qos(topic_qos); topic_qos.resource_limits.max_samples_per_instance = max_samples_per_instance ; topic_qos.history.depth = history_depth; ::DDS::Topic_var topic = dp->create_topic (MY_TOPIC, MY_TYPE, topic_qos, ::DDS::TopicListener::_nil(), ::OpenDDS::DCPS::DEFAULT_STATUS_MASK); if (CORBA::is_nil (topic.in ())) { return 1 ; } // Create the publisher ::DDS::Publisher_var pub = dp->create_publisher(PUBLISHER_QOS_DEFAULT, ::DDS::PublisherListener::_nil(), ::OpenDDS::DCPS::DEFAULT_STATUS_MASK); if (CORBA::is_nil (pub.in ())) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT("(%P|%t) create_publisher failed.\n")), 1); } // Create the datawriters ::DDS::DataWriterQos dw_qos; pub->get_default_datawriter_qos (dw_qos); dw_qos.history.depth = history_depth ; dw_qos.resource_limits.max_samples_per_instance = max_samples_per_instance ; dw_qos.liveliness.lease_duration.sec = LEASE_DURATION_SEC ; dw_qos.liveliness.lease_duration.nanosec = 0 ; ::DDS::DataWriter_var dw = pub->create_datawriter(topic.in (), dw_qos, ::DDS::DataWriterListener::_nil(), ::OpenDDS::DCPS::DEFAULT_STATUS_MASK); if (CORBA::is_nil (dw.in ())) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) create_datawriter failed.\n"))); return 1 ; } // ensure that the connection and association has been fully established ACE_OS::sleep(2); //TBD remove this kludge when the transport is fixed. // Indicate that the publisher is ready FILE* writers_ready = ACE_OS::fopen (pub_ready_filename.c_str (), ACE_TEXT("w")); if (writers_ready == 0) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: Unable to create publisher ready file\n"))); } // Wait for the subscriber to be ready. FILE* readers_ready = 0; do { ACE_Time_Value small_time(0,250000); ACE_OS::sleep (small_time); readers_ready = ACE_OS::fopen (sub_ready_filename.c_str (), ACE_TEXT("r")); } while (0 == readers_ready); ACE_OS::fclose(writers_ready); ACE_OS::fclose(readers_ready); ReactorCtrl rc ; // stop the Service_Participant reactor so LIVELINESS.kind=AUTOMATIC does not // send out an automatic liveliness control message when sleeping in the loop // below. rc.pause() ; Writer* writer = new Writer(dw.in (), 1, num_ops_per_thread); for (int i = 0 ; i < num_unlively_periods ; i++) { writer->run_test (i); // 3 ensures that we will detect when an DataReader detects // liveliness lost on an already unliveliy DataReader. ACE_OS::sleep (3 * LEASE_DURATION_SEC); } writer->run_test (num_unlively_periods); rc.resume() ; bool writers_finished = false; ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%P|%t) %T waiting for writers to finish\n") )); while ( !writers_finished ) { ACE_OS::sleep(ACE_Time_Value(0,250000)); writers_finished = true; writers_finished = writers_finished && writer->is_finished(); } ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%P|%t) %T Writers are finished\n") )); // Indicate that the publisher is done FILE* writers_completed = ACE_OS::fopen (pub_finished_filename.c_str (), ACE_TEXT("w")); if (writers_completed == 0) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) ERROR: Unable to create publisher completed file\n"))); } ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%P|%t) %T waiting for readers to finish\n") )); // Wait for the subscriber to finish. FILE* readers_completed = 0; do { ACE_Time_Value small_time(0,250000); ACE_OS::sleep (small_time); readers_completed = ACE_OS::fopen (sub_finished_filename.c_str (), ACE_TEXT("r")); } while (0 == readers_completed); ACE_OS::fclose(writers_completed); ACE_OS::fclose(readers_completed); ACE_DEBUG((LM_DEBUG,ACE_TEXT("(%P|%t) %T Readers are finished\n") )); // Clean up publisher objects pub->delete_contained_entities() ; delete writer; dp->delete_publisher(pub.in ()); dp->delete_topic(topic.in ()); dpf->delete_participant(dp.in ()); TheServiceParticipant->shutdown (); } catch (const TestException&) { ACE_ERROR ((LM_ERROR, ACE_TEXT("(%P|%t) TestException caught in main.cpp. "))); return 1; } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught in main.cpp:"); return 1; } return status; }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); CORBA::Object_var poa_object = orb->resolve_initial_references ("RootPOA"); if (CORBA::is_nil (poa_object.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Unable to initialize the POA.\n"), 1); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); // Policies for the childPOA to be created. CORBA::PolicyList policies (1); policies.length (1); CORBA::Any pol; pol <<= BiDirPolicy::BOTH; policies[0] = orb->create_policy (BiDirPolicy::BIDIRECTIONAL_POLICY_TYPE, pol); // Create POA as child of RootPOA with the above policies. This POA // will receive request in the same connection in which it sent // the request PortableServer::POA_var child_poa = root_poa->create_POA ("childPOA", poa_manager.in (), policies); // Creation of childPOA is over. Destroy the Policy objects. for (CORBA::ULong i = 0; i < policies.length (); ++i) { policies[i]->destroy (); } poa_manager->activate (); if (parse_args (argc, argv) != 0) return 1; Simple_Server_i *server_impl = 0; ACE_NEW_THROW_EX (server_impl, Simple_Server_i (orb.in (), no_iterations), CORBA::NO_MEMORY ()); PortableServer::ServantBase_var owner_transfer (server_impl); PortableServer::ObjectId_var id = PortableServer::string_to_ObjectId ("simple_server"); child_poa->activate_object_with_id (id.in (), server_impl); CORBA::Object_var obj = child_poa->id_to_reference (id.in ()); CORBA::String_var ior = orb->object_to_string (obj.in ()); ACE_DEBUG ((LM_DEBUG, "Activated as <%C>\n", ior.in ())); // If the ior_output_file exists, output the ior to it if (ior_output_file != 0) { FILE *output_file= ACE_OS::fopen (ior_output_file, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", ior_output_file), 1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); } // Run the event loop orb->run (); ACE_DEBUG ((LM_DEBUG, "event loop finished\n")); root_poa->destroy (1, 1); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Caught exception:"); return 1; } return 0; }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { int priority = (ACE_Sched_Params::priority_min (ACE_SCHED_FIFO) + ACE_Sched_Params::priority_max (ACE_SCHED_FIFO)) / 2; priority = ACE_Sched_Params::next_priority (ACE_SCHED_FIFO, priority); priority = ACE_Sched_Params::next_priority (ACE_SCHED_FIFO, priority); // Enable FIFO scheduling, e.g., RT scheduling class on Solaris. if (ACE_OS::sched_params (ACE_Sched_Params (ACE_SCHED_FIFO, priority, ACE_SCOPE_PROCESS)) != 0) { if (ACE_OS::last_error () == EPERM) { ACE_DEBUG ((LM_DEBUG, "server (%P|%t): user is not superuser, " "test runs in time-shared class\n")); } else ACE_ERROR ((LM_ERROR, "server (%P|%t): sched_params failed\n")); } try { CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); CORBA::Object_var poa_object = orb->resolve_initial_references("RootPOA"); if (CORBA::is_nil (poa_object.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Unable to initialize the POA.\n"), 1); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in ()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); if (parse_args (argc, argv) != 0) return 1; Roundtrip *roundtrip_impl; ACE_NEW_RETURN (roundtrip_impl, Roundtrip (orb.in ()), 1); PortableServer::ServantBase_var owner_transfer(roundtrip_impl); Test::Roundtrip_var roundtrip = roundtrip_impl->_this (); CORBA::String_var ior = orb->object_to_string (roundtrip.in ()); // If the ior_output_file exists, output the ior to it FILE *output_file= ACE_OS::fopen (ior_output_file, "w"); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", ior_output_file), 1); ACE_OS::fprintf (output_file, "%s", ior.in ()); ACE_OS::fclose (output_file); poa_manager->activate (); Server_Task server_task (orb.in ()); if (server_task.activate (THR_NEW_LWP | THR_JOINABLE, nthreads) != 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot activate server threads\n"), 1); server_task.thr_mgr ()->wait (); ACE_DEBUG ((LM_DEBUG, "event loop finished\n")); ACE_DEBUG ((LM_DEBUG, "(%P|%t) server - event loop finished\n")); root_poa->destroy (1, 1); orb->destroy (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("Exception caught:"); return 1; } return 0; }
int main(int argc, char **argv) { ra_pdsch_t ra_dl; int i; int frame_cnt; int ret; dci_location_t locations[MAX_CANDIDATES]; uint32_t nof_locations; dci_msg_t dci_msg; if (argc < 3) { usage(argv[0]); exit(-1); } parse_args(argc,argv); if (base_init()) { fprintf(stderr, "Error initializing memory\n"); exit(-1); } ret = -1; frame_cnt = 0; do { filesource_read(&fsrc, input_buffer, flen); INFO("Reading %d samples sub-frame %d\n", flen, frame_cnt); lte_fft_run_sf(&fft, input_buffer, fft_buffer); /* Get channel estimates for each port */ chest_dl_estimate(&chest, fft_buffer, ce, frame_cnt %10); uint16_t crc_rem = 0; if (pdcch_extract_llr(&pdcch, fft_buffer, ce, chest_dl_get_noise_estimate(&chest), frame_cnt %10, cfi)) { fprintf(stderr, "Error extracting LLRs\n"); return -1; } if (rnti == SIRNTI) { INFO("Initializing common search space for SI-RNTI\n",0); nof_locations = pdcch_common_locations(&pdcch, locations, MAX_CANDIDATES, cfi); } else { INFO("Initializing user-specific search space for RNTI: 0x%x\n", rnti); nof_locations = pdcch_ue_locations(&pdcch, locations, MAX_CANDIDATES, frame_cnt %10, cfi, rnti); } for (i=0;i<nof_locations && crc_rem != rnti;i++) { if (pdcch_decode_msg(&pdcch, &dci_msg, &locations[i], dci_format, &crc_rem)) { fprintf(stderr, "Error decoding DCI msg\n"); return -1; } } if (crc_rem == rnti) { dci_msg_type_t type; if (dci_msg_get_type(&dci_msg, &type, cell.nof_prb, rnti, 1234)) { fprintf(stderr, "Can't get DCI message type\n"); exit(-1); } printf("MSG %d: ",i); dci_msg_type_fprint(stdout, type); switch(type.type) { case PDSCH_SCHED: bzero(&ra_dl, sizeof(ra_pdsch_t)); if (dci_msg_unpack_pdsch(&dci_msg, &ra_dl, cell.nof_prb, rnti != SIRNTI)) { fprintf(stderr, "Can't unpack PDSCH message\n"); } else { ra_pdsch_fprint(stdout, &ra_dl, cell.nof_prb); if (ra_dl.alloc_type == alloc_type2 && ra_dl.type2_alloc.mode == t2_loc && ra_dl.type2_alloc.riv == 11 && ra_dl.rv_idx == 0 && ra_dl.harq_process == 0 && ra_dl.mcs_idx == 2) { printf("This is the file signal.1.92M.amar.dat\n"); ret = 0; } } break; default: fprintf(stderr, "Unsupported message type\n"); break; } } frame_cnt++; } while (frame_cnt <= max_frames); base_free(); exit(ret); }
/*--------------------------------------------------------------------------------* * main *--------------------------------------------------------------------------------*/ int main( int argc, char *argv[] ) { int rc, ind, total; pthread_t root_thread; parse_args( argc, argv ); /* Initialize node mutex. */ if ((rc = pthread_mutex_init(&node_mutex, NULL))) { tst_resm( TINFO, "pthread_mutex_init(node_mutex): %s", strerror(rc) ); testexit( 7 ); } /* Initialize node condition variable. */ if ((rc = pthread_cond_init(&node_condvar, NULL))) { tst_resm( TINFO, "pthread_cond_init(node_condvar): %s", strerror(rc) ); testexit( 8 ); } /* Allocate pthread info structure array. */ if ((total = num_nodes( breadth, depth )) > MAXTHREADS) { tst_resm( TINFO, "Can't create %d threads; max is %d.", total, MAXTHREADS ); testexit( 9 ); } tst_resm( TINFO, "Allocating %d nodes.", total ); if ((child_info = (c_info *)malloc( total * sizeof(c_info) )) == NULL) { perror( "malloc child_info" ); testexit( 10 ); } memset( child_info, 0x00, total * sizeof(c_info) ); if (debug) { printf( "Initializing array for %d children\n", total ); fflush( stdout ); } /* Allocate array of pthreads descriptors and initialize variables. */ for (ind = 0; ind < total; ind++) { if ( (child_info[ind].threads = (pthread_t *)malloc( breadth * sizeof(pthread_t) )) == NULL ) { perror( "malloc threads" ); testexit( 11 ); } memset( child_info[ind].threads, 0x00, breadth * sizeof(pthread_t) ); if ( (child_info[ind].child_ptrs = (c_info **)malloc( breadth * sizeof(c_info *) )) == NULL ) { perror( "malloc child_ptrs" ); testexit( 12 ); } memset( child_info[ind].child_ptrs, 0x00, breadth * sizeof(c_info *) ); if ((rc = pthread_mutex_init(&child_info[ind].child_mutex, NULL))) { tst_resm( TINFO, "pthread_mutex_init child_mutex: %s", strerror(rc) ); testexit( 13 ); } if ((rc = pthread_mutex_init(&child_info[ind].talk_mutex, NULL))) { tst_resm( TINFO, "pthread_mutex_init talk_mutex: %s", strerror(rc) ); testexit( 14 ); } if ((rc = pthread_cond_init(&child_info[ind].child_condvar, NULL))) { tst_resm( TINFO, "pthread_cond_init child_condvar: %s", strerror(rc) ); testexit( 15 ); } if ((rc = pthread_cond_init(&child_info[ind].talk_condvar, NULL))) { tst_resm( TINFO, "pthread_cond_init talk_condvar: %s", strerror(rc) ); testexit( 16 ); } if (debug) { printf( "Successfully initialized child %d.\n", ind ); fflush( stdout ); } } tst_resm( TINFO, "Creating root thread attributes via pthread_attr_init." ); if ((rc = pthread_attr_init(&attr))) { tst_resm( TINFO, "pthread_attr_init: %s", strerror(rc) ); testexit( 17 ); } /* Make sure that all the thread children we create have the * PTHREAD_CREATE_JOINABLE attribute. If they don't, then the * pthread_join call will sometimes fail and cause mass confusion. */ if ((rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE))) { tst_resm( TINFO, "pthread_attr_setdetachstate: %s", strerror(rc) ); testexit( 18 ); } tst_resm( TINFO, "Creating root thread via pthread_create." ); if ((rc = pthread_create(&root_thread, &attr, doit, NULL))) { tst_resm( TINFO, "pthread_create: %s", strerror(rc) ); testexit( 19 ); } if (debug) { printf( "Doing pthread_join.\n" ); fflush( stdout ); } /* Wait for the root child to exit. */ if ((rc = pthread_join(root_thread, NULL))) { tst_resm( TINFO, "pthread_join: %s", strerror(rc) ); testexit( 20 ); } if (debug) { printf( "About to pthread_exit.\n" ); fflush( stdout ); } tst_resm(TINFO, "The sum of tree (breadth %d, depth %d) is %ld", breadth, depth, child_info[0].sum); testexit( 0 ); exit(0); }
int main(int argc, char** argv) { int ret; setup_dir(); /* init globals */ gcc = sa_concat(gcc, "gcc"); /* replaced laterwards if c++ */ gcc = sa_concat(gcc, "-I."); src_lines = sa_concat(src_lines, "#define __LARGE_C__ " VERSION_INT_STR "\n" "#ifdef __cplusplus\n" "extern \"C\" {\n" "#endif\n" "#include <stdio.h>\n" "#include <stdlib.h>\n" "#ifdef __cplusplus\n" "}\n" "#include <iostream>\n" "using namespace std;\n" "#endif\n" "\n" "__LARGE_C_PREFIX__\n"); argv++; { /* parse args, determine cache dir */ char** new_argv = parse_args(argv, NULL, 0); for (; argv != new_argv; argv++) { add_spec(*argv, strlen(*argv) + 1); } if (! keep_files && (oneliner || *argv != NULL)) { struct stat st; if (oneliner) { build_store_dir(); } else if (stat(*argv, &st) == 0) { add_spec(*argv, strlen(*argv) + 1); add_spec(&st.st_size, sizeof(st.st_size)); add_spec(&st.st_mtime, sizeof(st.st_mtime)); build_store_dir(); } } } /* use cache if possible */ if (store_dir != NULL && check_specs()) { char** child_argv = NULL; #ifdef _WIN32 _utime(store_dir, NULL); /* update mtime of the directory */ #else utimes(store_dir, NULL); /* update mtime of the directory */ #endif exec_file = str_concat(str_dup(store_dir), "/"A_OUT); child_argv = sa_concat(child_argv, exec_file); #ifdef _WIN32 { int status; ret = spawn_w32(child_argv, &status); if (status == 0) exit(ret); } #else execv(exec_file, child_argv); #endif // if execv failed, we compile free(exec_file); remove_dir(store_dir); } /* prepare files */ make_temp_dir(); exec_file = str_concat(str_dup(temp_dir), "/"A_OUT); c_file = str_concat(str_dup(temp_dir), "/source.c"); if ((src_fp = fopen(c_file, "wt")) == NULL) { cmd_error("failed to create temporary file: %s : %s\n", c_file, strerror(errno)); } while (src_lines != NULL && *src_lines != NULL) { fputs(*src_lines++, src_fp); } /* write source with adjustments */ if (! oneliner) { FILE* fp; char* file; char* line; int line_no = 0; if (argv[0] == NULL) { fp = stdin; file = "stdin"; } else if (strcmp(argv[0], "-") == 0) { fp = stdin; argv++; file = "stdin"; } else { file = *argv++; if ((fp = fopen(file, "rt")) == NULL) { cmd_error("cannot open file: %s : %s\n", file, strerror(errno)); } fprintf(src_fp, "# 1 \"%s\" 1\n", file); } while ((line = get_line(fp)) != NULL) { int comment_out = 0; line_no++; if (line_no == 1 && strncmp(line, "#!", 2) == 0) { comment_out = 1; } else if (line[0] == '#') { char* buf = str_dup(line + 1); char** tokens = split_tokens(buf); if (*tokens != NULL) { if (strcmp(tokens[0], "option") == 0) { parse_args(tokens + 1, file, line_no); comment_out = 1; } } free(buf); free(tokens); } if (comment_out == 1) { fprintf(src_fp, "// "); } fputs(line, src_fp); } fputs("\n", src_fp); if (fp != stdin) { fclose(fp); } } /* close source file */ fputs("__LARGE_C_SUFFIX__\n", src_fp); fclose(src_fp); src_fp = NULL; /* compile */ if (use_plusplus) { gcc[0] = "g++"; } if (use_main) { gcc = sa_concat(gcc, "-D__LARGE_C_PREFIX__="); gcc = sa_concat(gcc, "-D__LARGE_C_SUFFIX__="); } else { gcc = sa_concat(gcc, "-D__LARGE_C_PREFIX__=int main(int argc, char** argv) {"); gcc = sa_concat(gcc, "-D__LARGE_C_SUFFIX__=; return 0; }"); } gcc = sa_concat(gcc, "-o"); gcc = sa_concat(gcc, show_disassembly ? "-" : exec_file); gcc = sa_concat(gcc, c_file); gcc = sa_merge(gcc, lopts); if ((ret = call_proc(gcc, "could not execute compiler")) != 0) { cleanup(); exit(ret); } if (show_disassembly) { cleanup(); exit(0); } { /* execute */ char** child_argv = NULL; if (use_debugger) { child_argv = sa_concat(child_argv, "gdb"); } child_argv = sa_concat(child_argv, exec_file); child_argv = sa_merge(child_argv, argv); ret = call_proc(child_argv, "could not spawn child process"); } /* move temp_dir to store_dir, if possible. * or, remove work_dir */ if (store_dir == NULL) { cleanup(); } else { save_specs(); update_cache(); if (rename(temp_dir, store_dir) != 0) { cleanup(); } } return ret; }
static void cmd_write_long_value(struct client *cli, char *cmd_str) { int opt, i, val; char *argvbuf[516]; char **argv = argvbuf; int argc = 1; uint16_t handle; uint16_t offset; char *endptr = NULL; int length; uint8_t *value = NULL; bool reliable_writes = false; if (!bt_gatt_client_is_ready(cli->gatt)) { printf("GATT client not initialized\n"); return; } if (!parse_args(cmd_str, 514, argv + 1, &argc)) { printf("Too many arguments\n"); write_value_usage(); return; } optind = 0; argv[0] = "write-long-value"; while ((opt = getopt_long(argc, argv, "+r", write_long_value_options, NULL)) != -1) { switch (opt) { case 'r': reliable_writes = true; break; default: write_long_value_usage(); return; } } argc -= optind; argv += optind; if (argc < 2) { write_long_value_usage(); return; } handle = strtol(argv[0], &endptr, 0); if (!endptr || *endptr != '\0' || !handle) { printf("Invalid handle: %s\n", argv[0]); return; } endptr = NULL; offset = strtol(argv[1], &endptr, 0); if (!endptr || *endptr != '\0' || errno == ERANGE) { printf("Invalid offset: %s\n", argv[1]); return; } length = argc - 2; if (length > 0) { if (length > UINT16_MAX) { printf("Write value too long\n"); return; } value = malloc(length); if (!value) { printf("Failed to construct write value\n"); return; } for (i = 2; i < argc; i++) { val = strtol(argv[i], &endptr, 0); if (endptr == argv[i] || *endptr != '\0' || errno == ERANGE || val < 0 || val > 255) { printf("Invalid value byte: %s\n", argv[i]); free(value); return; } value[i-2] = val; } } if (!bt_gatt_client_write_long_value(cli->gatt, reliable_writes, handle, offset, value, length, write_long_cb, NULL, NULL)) printf("Failed to initiate long write procedure\n"); free(value); }
int main(int argc, char ** argv) { int nprocs, mynod, errcode; options my_options = {NULL, 0, 0}; MPI_File fh; MPI_Status status; MPI_Info info; MPI_Init(&argc, &argv); MPI_Comm_size(MPI_COMM_WORLD, &nprocs); MPI_Comm_rank(MPI_COMM_WORLD, &mynod); parse_args(argc, argv, mynod, &my_options); if (my_options.do_aggregation) { MPI_Info_create(&info); MPI_Info_set(info, "romio_no_indep_rw", "true"); MPI_Info_set(info, "cb_config_list", "leela.mcs.anl.gov:1"); } else { info = MPI_INFO_NULL; } /* create the file w/o EXCL: this must not fail */ errcode = MPI_File_open(MPI_COMM_WORLD, my_options.fname, MPI_MODE_CREATE|MPI_MODE_RDWR, info, &fh); if (errcode != MPI_SUCCESS) { handle_error(errcode, "MPI_File_open"); } errcode = MPI_File_close(&fh); if (errcode != MPI_SUCCESS) { handle_error(errcode, "MPI_File_close"); } /* now try to open w/ CREAT|EXCL: this must fail */ errcode = MPI_File_open(MPI_COMM_WORLD, my_options.fname, MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_RDWR, info, &fh); if (errcode == MPI_SUCCESS) { handle_error(errcode, "MPI_File_open: expected an error: got"); } /* ignore the error: File_delete is not aggregator-aware */ MPI_File_delete(my_options.fname, info); /* this must succeed: the file no longer exists */ errcode = MPI_File_open(MPI_COMM_WORLD, my_options.fname, MPI_MODE_CREATE|MPI_MODE_EXCL|MPI_MODE_RDWR, info, &fh); if (errcode != MPI_SUCCESS) { handle_error(errcode, "MPI_File_open"); } errcode = MPI_File_close(&fh); if (errcode != MPI_SUCCESS) { handle_error(errcode, "MPI_File_close"); } if (mynod == 0) { printf(" No Errors\n"); } MPI_Finalize(); return 0; }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { try { // ORB initialization... CORBA::ORB_var orb = CORBA::ORB_init (argc, argv); if (parse_args (argc, argv) != 0) return 1; CORBA::Object_var poa_obj = orb->resolve_initial_references ("RootPOA"); PortableServer::POA_var poa = PortableServer::POA::_narrow (poa_obj.in ()); PortableServer::POAManager_var poa_manager = poa->the_POAManager (); poa_manager->activate (); // Obtain the event channel using the Naming Service. CORBA::Object_var nam_obj = orb->resolve_initial_references ("NameService" ); CosNaming::NamingContext_var root_context = CosNaming::NamingContext::_narrow(nam_obj.in ()); CosNaming::Name channel_name (1); channel_name.length (1); channel_name[0].id = CORBA::string_dup ("CountryEventChannel"); CORBA::Object_var ec_obj = root_context->resolve(channel_name); // Downcast the object reference to a TypedEventChannel reference CosTypedEventChannelAdmin::TypedEventChannel_var typed_event_channel = CosTypedEventChannelAdmin::TypedEventChannel::_narrow(ec_obj.in ()); // Initialise the Country Impl Country_i country (orb.in ()); Country_var typed_consumer = country._this(); // Connect to the typed channel CosTypedEventChannelAdmin::TypedConsumerAdmin_var typed_consumer_admin = typed_event_channel->for_consumers (); CosEventChannelAdmin::ProxyPushSupplier_var proxy_push_supplier = typed_consumer_admin->obtain_typed_push_supplier (_tc_Country->id()); proxy_push_supplier->connect_push_consumer (typed_consumer.in () ); CORBA::String_var str = orb->object_to_string (typed_consumer.in ()); FILE *output_file= ACE_OS::fopen (ACE_TEXT_ALWAYS_CHAR(ior_output_file), ACE_TEXT("w")); if (output_file == 0) ACE_ERROR_RETURN ((LM_ERROR, "Cannot open output file for writing IOR: %s", ior_output_file), 1); ACE_OS::fprintf (output_file, "%s", str.in ()); ACE_OS::fclose (output_file); // Wait for events. ACE_DEBUG ((LM_DEBUG, "Waiting on orb->run for events...\n")); orb->run (); ACE_DEBUG ((LM_DEBUG, "...ORB shutdown\n")); // Destroy the POA poa->destroy (1, 0); // Destroy the ORB orb->destroy (); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("main"); return 1; } return 0; }
int main(int argc, char *argv[]) { odph_linux_pthread_t thread_tbl[MAX_WORKERS]; appl_args_t params; int core_count, num_workers; odp_cpumask_t cpumask; char cpumaskstr[64]; struct rlimit rlp; getrlimit(RLIMIT_CORE, &rlp); printf("RLIMIT_CORE: %ld/%ld\n", rlp.rlim_cur, rlp.rlim_max); rlp.rlim_cur = 200000000; printf("Setting to max: %d\n", setrlimit(RLIMIT_CORE, &rlp)); /* Parse and store the application arguments */ parse_args(argc, argv, ¶ms); /* Print both system and application information */ print_info(NO_PATH(argv[0]), ¶ms); if (odp_init_global(NULL, NULL)) { OFP_ERR("Error: ODP global init failed.\n"); exit(EXIT_FAILURE); } if (odp_init_local(ODP_THREAD_CONTROL)) { OFP_ERR("Error: ODP local init failed.\n"); exit(EXIT_FAILURE); } core_count = odp_cpu_count(); num_workers = core_count; if (params.core_count) num_workers = params.core_count; if (num_workers > MAX_WORKERS) num_workers = MAX_WORKERS; /* * By default core #0 runs Linux kernel background tasks. * Start mapping thread from core #1 */ memset(&app_init_params, 0, sizeof(app_init_params)); app_init_params.linux_core_id = 0; if (core_count > 1) num_workers--; num_workers = odp_cpumask_default_worker(&cpumask, num_workers); odp_cpumask_to_str(&cpumask, cpumaskstr, sizeof(cpumaskstr)); printf("Num worker threads: %i\n", num_workers); printf("first CPU: %i\n", odp_cpumask_first(&cpumask)); printf("cpu mask: %s\n", cpumaskstr); app_init_params.if_count = params.if_count; app_init_params.if_names = params.if_names; app_init_params.pkt_hook[OFP_HOOK_LOCAL] = fastpath_local_hook; if (ofp_init_global(&app_init_params)) { OFP_ERR("Error: OFP global init failed.\n"); exit(EXIT_FAILURE); } memset(thread_tbl, 0, sizeof(thread_tbl)); /* Start dataplane dispatcher worker threads */ ofp_linux_pthread_create(thread_tbl, &cpumask, default_event_dispatcher, ofp_eth_vlan_processing, ODP_THREAD_CONTROL ); /* other app code here.*/ /* Start CLI */ ofp_start_cli_thread(app_init_params.linux_core_id, params.conf_file); sleep(2); /* webserver */ if (setup_webserver(params.root_dir, params.laddr, params.lport)) { OFP_ERR("Error: Failed to setup webserver.\n"); exit(EXIT_FAILURE); } odph_linux_pthread_join(thread_tbl, num_workers); printf("End Main()\n"); return 0; }
int main (int argc, char **argv) { try { // print warm welcome std::cerr << visual_truncate_path (argv[0], 1) << " - " << PACKAGE_STRING << " (" << LV_REVISION << ") commandline tool - " << PACKAGE_URL << "\n"; // setup signal handlers setup_signal_handlers (); // default loglevel visual_log_set_verbosity (VISUAL_LOG_ERROR); // initialize LV Libvisual main {argc, argv}; // parse commandline arguments int parse_result = parse_args (argc, argv); if (parse_result < 0) { throw std::runtime_error ("Failed to parse arguments"); } if (parse_result > 0) { return EXIT_SUCCESS; } // Set system-wide random seed if (have_seed) { LV::System::instance()->set_rng_seed (seed); } // create new VisBin for video output LV::Bin bin; bin.set_supported_depth(VISUAL_VIDEO_DEPTH_ALL); bin.use_morph(false); // Let the bin manage plugins. There's a bug otherwise. if (!bin.connect(actor_name, input_name)) { throw std::runtime_error ("Failed to start pipeline with actor '" + actor_name + "' and input '" + input_name + "'"); } auto actor = bin.get_actor(); // Select output colour depth VisVideoDepth depth; int depthflag = actor->get_supported_depths (); // Pick the best display depth directly supported by non GL actor if(depthflag != VISUAL_VIDEO_DEPTH_GL) { if (color_depth == 0) { depth = visual_video_depth_get_highest_nogl (depthflag); } // Pick user chosen colordepth else { depth = visual_video_depth_from_bpp (color_depth); } } /* GL actor */ else { depth = visual_video_depth_get_highest (depthflag); } bin.set_depth (depth); auto vidoptions = actor->get_video_attribute_options (); // initialize display Display display (driver_name); // create display auto video = display.create(depth, vidoptions, width, height, true); if(!video) { throw std::runtime_error("Failed to setup display for rendering"); } // Set the display title display.set_title(_("lv-tool")); // put it all together bin.set_video(video); bin.realize(); bin.sync(false); bin.depth_changed(); bin.set_morph(morph_name); // get a queue to handle events LV::EventQueue localqueue; // rendering statistics uint64_t frames_drawn = 0; // frame rate control state uint64_t const frame_period_us = frame_rate > 0 ? VISUAL_USECS_PER_SEC / frame_rate : 0; LV::Time last_frame_time; bool draw_frame = true; // main loop bool running = true; //bool visible = true; while (running) { // Check if process termination was signaled if (terminate_process) { std::cerr << "Received signal to terminate process, exiting..\n"; return EXIT_SUCCESS; } // Control frame rate if (frame_rate > 0) { if (frames_drawn > 0) { draw_frame = (LV::Time::now () - last_frame_time).to_usecs () >= frame_period_us; } } if (draw_frame) { DisplayLock lock {display}; // Draw audio data and render bin.run(); // Display rendering display.update_all (); // Record frame time last_frame_time = LV::Time::now (); // All frames rendered? frames_drawn++; if (frame_count > 0 && frames_drawn >= frame_count) { break; } // switch actor? if (actor_switch_after_frames > 0 && frames_drawn >= actor_switch_after_frames + actor_switch_framecount) { actor_switch_framecount += actor_switch_after_frames; actor_name = cycle_actor_name (actor_name, CycleDir::NEXT); std::cerr << "Switching to actor '" << actor_name << "'...\n"; bin.switch_actor (actor_name); } } LV::Event ev; // Handle all events display.drain_events(localqueue); auto pluginqueue = visual_plugin_get_event_queue (bin.get_actor()->get_plugin ()); while (localqueue.poll(ev)) { if(ev.type != VISUAL_EVENT_RESIZE) pluginqueue->add (ev); switch (ev.type) { case VISUAL_EVENT_PARAM: { break; } case VISUAL_EVENT_RESIZE: { DisplayLock lock {display}; width = ev.event.resize.width; height = ev.event.resize.height; video = display.create(depth, vidoptions, width, height, true); display.set_title(_("lv-tool")); bin.set_video (video); bin.sync(false); break; } case VISUAL_EVENT_MOUSEMOTION: { break; } case VISUAL_EVENT_MOUSEBUTTONDOWN: { // switch to next actor actor_name = cycle_actor_name (actor_name, CycleDir::NEXT); std::cerr << "Switching to actor '" << actor_name << "'...\n"; bin.switch_actor (actor_name); break; } case VISUAL_EVENT_MOUSEBUTTONUP: { break; } case VISUAL_EVENT_KEYDOWN: { switch(ev.event.keyboard.keysym.sym) { case VKEY_ESCAPE: { running = false; break; } case VKEY_TAB: { break; } default: break; } break; } case VISUAL_EVENT_KEYUP: { break; } case VISUAL_EVENT_QUIT: { running = false; break; } case VISUAL_EVENT_VISIBILITY: { //visible = ev.event.visibility.is_visible; break; } default: { break; } } } if (bin.depth_changed()) { DisplayLock lock {display}; int depthflag = bin.get_depth(); VisVideoDepth depth = visual_video_depth_get_highest(depthflag); display.create(depth, vidoptions, width, height, true); video = display.get_video(); bin.set_video(video); bin.sync(true); } } return EXIT_SUCCESS; } catch (std::exception& error) { std::cerr << error.what () << std::endl; return EXIT_FAILURE; } }
static int parse_dispatch_command(struct sftp_conn *conn, const char *cmd, char **pwd, int err_abort) { char *path1, *path2, *tmp; int pflag, lflag, iflag, cmdnum, i; unsigned long n_arg; Attrib a, *aa; char path_buf[MAXPATHLEN]; int err = 0; glob_t g; path1 = path2 = NULL; cmdnum = parse_args(&cmd, &pflag, &lflag, &iflag, &n_arg, &path1, &path2); if (iflag != 0) err_abort = 0; memset(&g, 0, sizeof(g)); /* Perform command */ switch (cmdnum) { case 0: /* Blank line */ break; case -1: /* Unrecognized command */ err = -1; break; case I_GET: err = process_get(conn, path1, path2, *pwd, pflag); break; case I_PUT: err = process_put(conn, path1, path2, *pwd, pflag); break; case I_RENAME: path1 = make_absolute(path1, *pwd); path2 = make_absolute(path2, *pwd); err = do_rename(conn, path1, path2); break; case I_SYMLINK: path2 = make_absolute(path2, *pwd); err = do_symlink(conn, path1, path2); break; case I_RM: path1 = make_absolute(path1, *pwd); remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g); for (i = 0; g.gl_pathv[i] && !interrupted; i++) { printf("Removing %s\n", g.gl_pathv[i]); err = do_rm(conn, g.gl_pathv[i]); if (err != 0 && err_abort) break; } break; case I_MKDIR: path1 = make_absolute(path1, *pwd); attrib_clear(&a); a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS; a.perm = 0777; err = do_mkdir(conn, path1, &a); break; case I_RMDIR: path1 = make_absolute(path1, *pwd); err = do_rmdir(conn, path1); break; case I_CHDIR: path1 = make_absolute(path1, *pwd); if ((tmp = do_realpath(conn, path1)) == NULL) { err = 1; break; } if ((aa = do_stat(conn, tmp, 0)) == NULL) { xfree(tmp); err = 1; break; } if (!(aa->flags & SSH2_FILEXFER_ATTR_PERMISSIONS)) { error("Can't change directory: Can't check target"); xfree(tmp); err = 1; break; } if (!S_ISDIR(aa->perm)) { error("Can't change directory: \"%s\" is not " "a directory", tmp); xfree(tmp); err = 1; break; } xfree(*pwd); *pwd = tmp; break; case I_LS: if (!path1) { do_globbed_ls(conn, *pwd, *pwd, lflag); break; } /* Strip pwd off beginning of non-absolute paths */ tmp = NULL; if (*path1 != '/') tmp = *pwd; path1 = make_absolute(path1, *pwd); err = do_globbed_ls(conn, path1, tmp, lflag); break; case I_LCHDIR: if (chdir(path1) == -1) { error("Couldn't change local directory to " "\"%s\": %s", path1, strerror(errno)); err = 1; } break; case I_LMKDIR: if (mkdir(path1, 0777) == -1) { error("Couldn't create local directory " "\"%s\": %s", path1, strerror(errno)); err = 1; } break; case I_LLS: local_do_ls(cmd); break; case I_SHELL: local_do_shell(cmd); break; case I_LUMASK: umask(n_arg); printf("Local umask: %03lo\n", n_arg); break; case I_CHMOD: path1 = make_absolute(path1, *pwd); attrib_clear(&a); a.flags |= SSH2_FILEXFER_ATTR_PERMISSIONS; a.perm = n_arg; remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g); for (i = 0; g.gl_pathv[i] && !interrupted; i++) { printf("Changing mode on %s\n", g.gl_pathv[i]); err = do_setstat(conn, g.gl_pathv[i], &a); if (err != 0 && err_abort) break; } break; case I_CHOWN: case I_CHGRP: path1 = make_absolute(path1, *pwd); remote_glob(conn, path1, GLOB_NOCHECK, NULL, &g); for (i = 0; g.gl_pathv[i] && !interrupted; i++) { if (!(aa = do_stat(conn, g.gl_pathv[i], 0))) { if (err != 0 && err_abort) break; else continue; } if (!(aa->flags & SSH2_FILEXFER_ATTR_UIDGID)) { error("Can't get current ownership of " "remote file \"%s\"", g.gl_pathv[i]); if (err != 0 && err_abort) break; else continue; } aa->flags &= SSH2_FILEXFER_ATTR_UIDGID; if (cmdnum == I_CHOWN) { printf("Changing owner on %s\n", g.gl_pathv[i]); aa->uid = n_arg; } else { printf("Changing group on %s\n", g.gl_pathv[i]); aa->gid = n_arg; } err = do_setstat(conn, g.gl_pathv[i], aa); if (err != 0 && err_abort) break; } break; case I_PWD: printf("Remote working directory: %s\n", *pwd); break; case I_LPWD: if (!getcwd(path_buf, sizeof(path_buf))) { error("Couldn't get local cwd: %s", strerror(errno)); err = -1; break; } printf("Local working directory: %s\n", path_buf); break; case I_QUIT: /* Processed below */ break; case I_HELP: help(); break; case I_VERSION: printf("SFTP protocol version %u\n", sftp_proto_version(conn)); break; case I_PROGRESS: showprogress = !showprogress; if (showprogress) printf("Progress meter enabled\n"); else printf("Progress meter disabled\n"); break; default: fatal("%d is not implemented", cmdnum); } if (g.gl_pathc) globfree(&g); if (path1) xfree(path1); if (path2) xfree(path2); /* If an unignored error occurs in batch mode we should abort. */ if (err_abort && err != 0) return (-1); else if (cmdnum == I_QUIT) return (1); return (0); }
int ACE_TMAIN(int argc, ACE_TCHAR *argv[]) { if (parse_args (argc, argv) != 0) { return 1; } // create initial data for supplier and consumer operations const int operation_count = 8; ACE_Scheduler_Factory::POD_RT_Info config_infos[operation_count] = { // good supplier (no unresolved dependencies) { "good_supplier", // entry point 0, // handle 5000, // worst case execution time 5000, // typical execution time (unused) 5000, // cached execution time 500000, // period (100 ns) RtecScheduler::HIGH_CRITICALITY, // criticality RtecScheduler::LOW_IMPORTANCE, // importance 0, // quantum (unused) 1, // threads 0, // OS priority 0, // Preemption subpriority 0, // Preemption priority RtecScheduler::OPERATION // info type }, // good consumer (no unresolved dependencies) { "good_consumer", // entry point 1, // handle 5000, // worst case execution time 5000, // typical execution time (unused) 5000, // cached execution time 0, // period (100 ns) RtecScheduler::HIGH_CRITICALITY, // criticality RtecScheduler::LOW_IMPORTANCE, // importance 0, // quantum (unused) 0, // threads 0, // OS priority 0, // Preemption subpriority 0, // Preemption priority RtecScheduler::OPERATION // info type }, // supplier with unresolved remote dependencies { "unresolved_remote_supplier", // entry point 2, // handle 5000, // worst case execution time 5000, // typical execution time (unused) 5000, // cached execution time 0, // period (100 ns) RtecScheduler::HIGH_CRITICALITY, // criticality RtecScheduler::LOW_IMPORTANCE, // importance 0, // quantum (unused) 0, // threads 0, // OS priority 0, // Preemption subpriority 0, // Preemption priority RtecScheduler::REMOTE_DEPENDANT // info type }, // consumer with unresolved remote dependencies { "unresolved_remote_consumer", // entry point 3, // handle 5000, // worst case execution time 5000, // typical execution time (unused) 5000, // cached execution time 0, // period (100 ns) RtecScheduler::HIGH_CRITICALITY, // criticality RtecScheduler::LOW_IMPORTANCE, // importance 0, // quantum (unused) 0, // threads 0, // OS priority 0, // Preemption subpriority 0, // Preemption priority RtecScheduler::OPERATION // info type }, // supplier with unresolved local dependencies { "unresolved_local_supplier", // entry point 4, // handle 5000, // worst case execution time 5000, // typical execution time (unused) 5000, // cached execution time 0, // period (100 ns) RtecScheduler::HIGH_CRITICALITY, // criticality RtecScheduler::LOW_IMPORTANCE, // importance 0, // quantum (unused) 0, // threads 0, // OS priority 0, // Preemption subpriority 0, // Preemption priority RtecScheduler::OPERATION // info type }, // consumer with unresolved local dependencies { "unresolved_local_consumer", // entry point 5, // handle 5000, // worst case execution time 5000, // typical execution time (unused) 5000, // cached execution time 0, // period (100 ns) RtecScheduler::HIGH_CRITICALITY, // criticality RtecScheduler::LOW_IMPORTANCE, // importance 0, // quantum (unused) 0, // threads 0, // OS priority 0, // Preemption subpriority 0, // Preemption priority RtecScheduler::OPERATION // info type }, // consumer with unresolved local and remote dependencies { "both_unresolved_consumer_1", // entry point 6, // handle 5000, // worst case execution time 5000, // typical execution time (unused) 5000, // cached execution time 0, // period (100 ns) RtecScheduler::HIGH_CRITICALITY, // criticality RtecScheduler::LOW_IMPORTANCE, // importance 0, // quantum (unused) 0, // threads 0, // OS priority 0, // Preemption subpriority 0, // Preemption priority RtecScheduler::OPERATION // info type }, // another consumer with unresolved // local and remote dependencies { "both_unresolved_consumer_2", // entry point 7, // handle 5000, // worst case execution time 5000, // typical execution time (unused) 5000, // cached execution time 0, // period (100 ns) RtecScheduler::HIGH_CRITICALITY, // criticality RtecScheduler::LOW_IMPORTANCE, // importance 0, // quantum (unused) 0, // threads 0, // OS priority 0, // Preemption subpriority 0, // Preemption priority RtecScheduler::OPERATION // info type } }; try { // Initialize ORB. CORBA::ORB_var orb = CORBA::ORB_init (argc, argv, "internet"); CORBA::Object_var poa_object = orb->resolve_initial_references("RootPOA"); if (CORBA::is_nil(poa_object.in ())) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Unable to initialize the POA.\n"), 1); PortableServer::POA_var root_poa = PortableServer::POA::_narrow (poa_object.in()); PortableServer::POAManager_var poa_manager = root_poa->the_POAManager (); // Initialize the naming services TAO_Naming_Client my_name_client; if (my_name_client.init (orb.in ()) != 0) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Unable to initialize " "the TAO_Naming_Client.\n"), -1); CosNaming::NamingContext_var context = my_name_client.get_context (); if (ACE_Scheduler_Factory::use_config (context.in (), service_name) < 0) ACE_ERROR_RETURN ((LM_ERROR, " (%P|%t) Unable to bind to the scheduling service.\n"), 1); // create and initialize RT_Infos in the scheduler, // make second half of array depend on first half. for (int i = 0; i < operation_count; ++i) { // create the RT_Info config_infos[i].handle = ACE_Scheduler_Factory::server ()->create (config_infos[i].entry_point); // initialize the RT_Info ACE_Scheduler_Factory::server ()-> set (config_infos[i].handle, static_cast<RtecScheduler::Criticality_t> (config_infos[i].criticality), config_infos[i].worst_case_execution_time, config_infos[i].typical_execution_time, config_infos[i].cached_execution_time, config_infos[i].period, static_cast<RtecScheduler::Importance_t> (config_infos[i].importance), config_infos[i].quantum, config_infos[i].threads, static_cast<RtecScheduler::Info_Type_t> (config_infos[i].info_type)); } // register dependency of good consumer on good supplier ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[1].handle, config_infos[0].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); // register dependency of consumer that will have unresolved remote // dependencies on supplier with unresolved remote dependencies ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[3].handle, config_infos[2].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); // register dependency of consumer that will have unresolved local // dependencies on supplier with unresolved local dependencies ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[5].handle, config_infos[4].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); // register dependencies on each supplier of first consumer that will // have both unresolved local and unresolved remote dependencies. ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[6].handle, config_infos[0].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[6].handle, config_infos[2].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[6].handle, config_infos[4].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); // Register dependencies on each of the other consumers by second // consumer that will have both unresolved local and unresolved remote // dependencies. ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[7].handle, config_infos[1].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[7].handle, config_infos[3].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[7].handle, config_infos[5].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); ACE_Scheduler_Factory::server ()-> add_dependency (config_infos[7].handle, config_infos[6].handle, 1, // number of calls RtecBase::ONE_WAY_CALL // type of dependency ); RtecScheduler::RT_Info_Set_var infos; RtecScheduler::Dependency_Set_var deps; RtecScheduler::Config_Info_Set_var configs; RtecScheduler::Scheduling_Anomaly_Set_var anomalies; ACE_Scheduler_Factory::server ()->compute_scheduling (ACE_Sched_Params::priority_min (ACE_SCHED_FIFO, ACE_SCOPE_THREAD), ACE_Sched_Params::priority_max (ACE_SCHED_FIFO, ACE_SCOPE_THREAD), infos.out (), deps.out (), configs.out (), anomalies.out ()); ACE_Scheduler_Factory::dump_schedule (infos.in (), deps.in (), configs.in (), anomalies.in (), "Sched_Conf_Anomalies_Runtime.h", format_string); } catch (const CORBA::Exception& ex) { ex._tao_print_exception ("SYS_EX"); } return 0; }
int main( int argc, char *argv[]) { const char *firmware = NULL; char xmodem_buffer[69]; char cmdstr[80]; int status, i; xbee_serial_t XBEE_SERPORT; FILE *fw_file = NULL; #ifdef VERBOSE uint16_t last_state; #endif uint16_t last_packet; target_t *target = NULL; // turn off buffering so status changes (lines ending in \r) display setvbuf( stdout, NULL, _IONBF, 0); memset( target_list, 0, sizeof target_list); // set serial port parse_serial_arguments( argc, argv, &XBEE_SERPORT); // parse args for this program parse_args( argc, argv); // initialize the serial and device layer for this XBee device if (xbee_dev_init( &my_xbee, &XBEE_SERPORT, NULL, NULL)) { printf( "Failed to initialize device.\n"); return 0; } // Initialize the WPAN layer of the XBee device driver. This layer enables // endpoints and clusters, and is required for all ZigBee layers. xbee_wpan_init( &my_xbee, &sample_endpoints.zdo); // Initialize the AT Command layer for this XBee device and have the // driver query it for basic information (hardware version, firmware version, // serial number, IEEE address, etc.) xbee_cmd_init_device( &my_xbee); printf( "Waiting for driver to query the XBee device...\n"); do { xbee_dev_tick( &my_xbee); status = xbee_cmd_query_status( &my_xbee); } while (status == -EBUSY); if (status) { printf( "Error %d waiting for query to complete.\n", status); } // report on the settings xbee_dev_dump_settings( &my_xbee, XBEE_DEV_DUMP_FLAG_DEFAULT); print_help(); if (dynamic_profile.profile_id != 0) { printf( "Using profile ID 0x%04x with%s APS encryption.\n", dynamic_profile.profile_id, (dynamic_profile.flags & WPAN_CLUST_FLAG_ENCRYPT) ? "" : "out"); xbee_ota_find_devices( &my_xbee.wpan_dev, xbee_found, NULL); } while (1) { while (xbee_readline( cmdstr, sizeof cmdstr) == -EAGAIN) { wpan_tick( &my_xbee.wpan_dev); if (fw_file != NULL) { if (xbee_xmodem_tx_tick( &xbee_ota.xbxm) != 0) { uint16_t timer; printf( "upload complete \n"); fclose( fw_file); fw_file = NULL; // wait one second for device to reboot then rediscover it timer = XBEE_SET_TIMEOUT_MS(1000); while (! XBEE_CHECK_TIMEOUT_MS( timer)); xbee_ota_find_devices( &my_xbee.wpan_dev, xbee_found, NULL); } #ifdef VERBOSE if (last_state != xbee_ota.xbxm.state) { printf( "state change from %u to %u\n", last_state, xbee_ota.xbxm.state); last_state = xbee_ota.xbxm.state; } #endif if (last_packet != xbee_ota.xbxm.packet_num) { #ifdef VERBOSE printf( "packet #%u\n", xbee_ota.xbxm.packet_num); #else printf( " %" PRIu32 " bytes\r", UINT32_C(64) * xbee_ota.xbxm.packet_num); #endif last_packet = xbee_ota.xbxm.packet_num; } } } if (! strcmpi( cmdstr, "quit")) { return 0; } else if (! strcmpi( cmdstr, "help") || ! strcmp( cmdstr, "?")) { print_help(); } else if (! strcmpi( cmdstr, "find")) { if (dynamic_profile.profile_id == 0) { puts( "Error: specify a profile via cmd line or 'profile' cmd"); } else { xbee_ota_find_devices( &my_xbee.wpan_dev, xbee_found, NULL); } } else if (! strncmpi( cmdstr, "profile ", 8)) { dynamic_profile.profile_id = strtoul( &cmdstr[8], NULL, 16); printf( "Profile ID set to 0x%04x\n", dynamic_profile.profile_id); profile_changed(); } else if (! strcmpi( cmdstr, "target")) { puts( " #: --IEEE Address--- Ver. --------Application Name--------" " ---Date Code----"); for (i = 0; i < target_index; ++i) { print_target( i); } puts( "End of List"); } else if (! strncmpi( cmdstr, "target ", 7)) { i = (int) strtoul( &cmdstr[7], NULL, 10); if (target_index == 0) { printf( "error, no targets in list, starting search now...\n"); xbee_ota_find_devices( &my_xbee.wpan_dev, xbee_found, NULL); } else if (i < 0 || i >= target_index) { printf( "error, index %d is invalid (must be 0 to %u)\n", i, target_index - 1); } else { target = &target_list[i]; puts( "set target to:"); print_target( i); } } else if (! strcmpi( cmdstr, "F") && target != NULL) { // If the target is stuck in the bootloader, send an 'F' to start // a firmware update. wpan_envelope_t envelope; wpan_envelope_create( &envelope, &my_xbee.wpan_dev, &target->ieee, WPAN_NET_ADDR_UNDEFINED); envelope.options = current_profile->flags; xbee_transparent_serial_str( &envelope, "F"); } else if (! strcmpi( cmdstr, "firmware")) { firmware = get_file(); } else if (! strcmpi( cmdstr, "password")) { set_password( ""); puts( "cleared password (will use default of a single null byte)"); } else if (! strncmpi( cmdstr, "password ", 9)) { set_password( &cmdstr[9]); printf( "set password to [%.*s]\n", xbee_ota.auth_length, xbee_ota.auth_data); } else if (! strcmpi( cmdstr, "aps")) { xbee_ota.flags ^= XBEE_OTA_FLAG_APS_ENCRYPT; printf( "APS encryption %sabled\n", (xbee_ota.flags & XBEE_OTA_FLAG_APS_ENCRYPT) ? "en" : "dis"); } else if (! strcmpi( cmdstr, "go")) { if (target == NULL) { if (target_index > 0) { target = &target_list[0]; } else { puts( "no targets available to send to"); continue; } } if (firmware == NULL) { firmware = get_file(); if (firmware == NULL) { printf( "Canceled.\n"); continue; } } printf( "Starting xmodem upload of\n %s\n", firmware); fw_file = fopen( firmware, "rb"); if (! fw_file) { printf( "Failed to open '%s'\n", firmware); exit( -1); } status = xbee_ota_init( &xbee_ota, &my_xbee.wpan_dev, &target->ieee); if (status) { printf( "%s returned %d\n", "xbee_ota_init", status); continue; } status = xbee_xmodem_set_source( &xbee_ota.xbxm, xmodem_buffer, fw_read, fw_file); if (status) { printf( "%s returned %d\n", "xbee_xmodem_set_source", status); continue; } // reset the xbee_xmodem_state_t state machine, keeping existing flags status = xbee_xmodem_tx_init( &xbee_ota.xbxm, xbee_ota.xbxm.flags); if (status) { printf( "%s returned %d\n", "xbee_xmodem_tx_init", status); continue; } // reset copies of basic cluster -- need to refresh after update memset( &target->basic, 0, sizeof(target->basic)); #ifdef VERBOSE last_state = last_packet = 0; #endif // main loop will tick the xmodem transfre until fw_file == NULL } #ifdef XBEE_XMODEM_TESTING else if (! strcmpi( cmdstr, "ACK")) { xbee_ota.xbxm.flags |= XBEE_XMODEM_FLAG_DROP_ACK; } else if (! strcmpi( cmdstr, "FRAME")) { xbee_ota.xbxm.flags |= XBEE_XMODEM_FLAG_DROP_FRAME; } else if (! strcmpi( cmdstr, "CRC")) { xbee_ota.xbxm.flags |= XBEE_XMODEM_FLAG_BAD_CRC; } #endif else if (! strncmpi( cmdstr, "AT", 2)) { process_command( &my_xbee, &cmdstr[2]); } else { printf( "unknown command: '%s'\n", cmdstr); } } }