static bool do_reset_proc(atrt_config& config, SqlResultSet& command, AtrtClient& atrtdb){ uint process_id= command.columnAsInt("process_id"); g_logger.info("Reset process: %d", process_id); // Get the process if (process_id > config.m_processes.size()){ g_logger.critical("Invalid process id %d", process_id); return false; } atrt_process& proc= *config.m_processes[process_id]; g_logger.info("stopping process..."); if (!stop_process(proc)) return false; if (proc.m_save.m_saved) { ndbout << "before: " << proc << endl; proc.m_proc= proc.m_save.m_proc; proc.m_save.m_saved= false; proc.m_proc.m_id= -1; ndbout << "after: " << proc << endl; } else { ndbout << "process has not changed" << endl; } g_logger.info("starting process..."); if (!start_process(proc)) return false; return true; }
void Compete() { int i; ir_transmit_off(); fAssertEnable = YesNo("Debug"); kill_process(ipMotor); if (YesNo("Start Light")) start_machine(START_LIGHT_PORT); ipMotor = start_process(MotorDriver()); CompeteInit(0); Orient(); while (1) { FindLine(); CollectBalls(); /* BUG: We don't really know if we have a ball here */ DumpBall(); ReturnForMore(); } printf("C1"); }
void start(procnanny_t *pn, program_t *program) { pn_prog_init(program); int nprocs = 50; pn_prog_set(program, PROGRAM_NAME, "hello world", 11); pn_prog_set(program, PROGRAM_USER, "jls", -1); pn_prog_set(program, PROGRAM_NUMPROCS, &nprocs, sizeof(int)); const char *command = "/usr/bin/env"; const char **args = calloc(3, sizeof(char *)); args[0] = "ruby"; args[1] = "-e"; args[2] = "sleep(rand * 20); puts 'hello world'; exit((rand * 10).to_i)"; program->nice = 5; pn_prog_set(program, PROGRAM_COMMAND, command, strlen(command)); pn_prog_set(program, PROGRAM_ARGS, args, 3); pn_prog_proc_each(program, i, process, { pn_proc_move_state(process, PROCESS_STATE_NEW); start_process(pn, process); });
/** * Handle START-message. * * @param cls closure (always NULL) * @param client identification of the client * @param message the actual message * @return GNUNET_OK to keep the connection open, * GNUNET_SYSERR to close it (signal serious error) */ static void handle_start (void *cls, struct GNUNET_SERVER_Client *client, const struct GNUNET_MessageHeader *message) { const char *servicename; struct ServiceList *sl; uint16_t size; size = ntohs (message->size); size -= sizeof (struct GNUNET_MessageHeader); servicename = (const char *) &message[1]; if ((size == 0) || (servicename[size - 1] != '\0')) { GNUNET_break (0); GNUNET_SERVER_receive_done (client, GNUNET_SYSERR); return; } if (GNUNET_YES == in_shutdown) { signal_result (client, servicename, GNUNET_ARM_PROCESS_SHUTDOWN); return; } sl = find_service (servicename); if (NULL == sl) { signal_result (client, servicename, GNUNET_ARM_PROCESS_UNKNOWN); return; } sl->is_default = GNUNET_YES; if (sl->proc != NULL) { signal_result (client, servicename, GNUNET_ARM_PROCESS_ALREADY_RUNNING); return; } start_process (sl); signal_result (client, servicename, GNUNET_ARM_PROCESS_STARTING); }
void kissSim_init(int world, int rx, int ry, float rt) { int i,splash=1; if(world<0){world=-world; splash=0;}//a negative world means no splash screen kissSimLoadWorld(world);//sets .world, .simHeight & .simWidth (leaving default values if sim is smaller) kissSimRobotDim(&ksWindow.rWidth, &ksWindow.rHeight);//set robot window dimensions ksWindow.height=ksWindow.simHeight+ksWindow.rHeight;//set overall window height kissSimComputerDim(&ksWindow.cWidth, &ksWindow.cHeight);//set computer window dimentsions ksWindow.width=ksWindow.simWidth+ksWindow.cWidth;//set overall window width graphics_init(ksWindow.width, ksWindow.height); graphics_fill(255,255,255); glfwSetWindowTitle(_world.title); // Draw the spash screen if(splash)kissSplashBG(ksWindow.width, ksWindow.height); robot.x=rx; robot.y=ry; robot.theta=rt; kissSimRobotInit(); kissSimComputerInit(); graphics_rectangle_fill(0,0,ksWindow.simWidth-1,ksWindow.simHeight-1,255,200,200);// instruction background is light pink kissSimPrintInstructions(); graphics_update(); while(!kiss_get_key(' '));while(kiss_get_key(' '));//pause until space bar is hit start_process(kissSimInBgd); kissSimPause(); }
int broker_os_add_qpid_route(const struct mh_qpid_route *route) { wchar_t cmd[1024]; if (route->aggregate && route->srclocal) { snwprintf(cmd, sizeof(cmd) / sizeof(*cmd), L"%ls --src-local route add %s %s %s %s", QPID_ROUTE, route->dest, route->src, route->exchange, route->route_key); } else if (route->aggregate) { snwprintf(cmd, sizeof(cmd) / sizeof(*cmd), L"%ls route add %s %s %s %s", QPID_ROUTE, route->dest, route->src, route->exchange, route->route_key); } else { snwprintf(cmd, sizeof(cmd) / sizeof(*cmd), L"%ls --timeout=5 dynamic add %s %s %s", QPID_ROUTE, route->dest, route->src, route->exchange); } if (start_process(QPID_ROUTE, cmd)) { return -1; } return 0; }
/** * Task run whenever it is time to restart a child that died. * * @param cls closure, always NULL * @param tc context */ static void delayed_restart_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc) { struct ServiceList *sl; struct GNUNET_TIME_Relative lowestRestartDelay; struct ServiceListeningInfo *sli; child_restart_task = GNUNET_SCHEDULER_NO_TASK; if (0 != (tc->reason & GNUNET_SCHEDULER_REASON_SHUTDOWN)) return; GNUNET_assert (GNUNET_NO == in_shutdown); lowestRestartDelay = GNUNET_TIME_UNIT_FOREVER_REL; /* check for services that need to be restarted due to * configuration changes or because the last restart failed */ for (sl = running_head; NULL != sl; sl = sl->next) { if (NULL != sl->proc) continue; /* service is currently not running */ if (GNUNET_TIME_absolute_get_remaining (sl->restart_at).rel_value == 0) { /* restart is now allowed */ if (sl->is_default) { /* process should run by default, start immediately */ GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Restarting service `%s'.\n"), sl->name); start_process (sl); } else { /* process is run on-demand, ensure it is re-started if there is demand */ for (sli = sl->listen_head; NULL != sli; sli = sli->next) if (GNUNET_SCHEDULER_NO_TASK == sli->accept_task) { /* accept was actually paused, so start it again */ sli->accept_task = GNUNET_SCHEDULER_add_read_net (GNUNET_TIME_UNIT_FOREVER_REL, sli->listen_socket, &accept_connection, sli); } } } else { /* update calculation for earliest time to reactivate a service */ lowestRestartDelay = GNUNET_TIME_relative_min (lowestRestartDelay, GNUNET_TIME_absolute_get_remaining (sl->restart_at)); } } if (lowestRestartDelay.rel_value != GNUNET_TIME_UNIT_FOREVER_REL.rel_value) { GNUNET_log (GNUNET_ERROR_TYPE_DEBUG, "Will restart process in %llums\n", (unsigned long long) lowestRestartDelay.rel_value); child_restart_task = GNUNET_SCHEDULER_add_delayed_with_priority (lowestRestartDelay, GNUNET_SCHEDULER_PRIORITY_IDLE, &delayed_restart_task, NULL); } }
proc_id sys_start_process(char* command) { return start_process(command); }
/** * Process arm requests. * * @param cls closure * @param serv the initialized server * @param c configuration to use */ static void run (void *cls, struct GNUNET_SERVER_Handle *serv, const struct GNUNET_CONFIGURATION_Handle *c) { static const struct GNUNET_SERVER_MessageHandler handlers[] = { {&handle_start, NULL, GNUNET_MESSAGE_TYPE_ARM_START, 0}, {&handle_stop, NULL, GNUNET_MESSAGE_TYPE_ARM_STOP, 0}, {&handle_shutdown, NULL, GNUNET_MESSAGE_TYPE_ARM_SHUTDOWN, sizeof (struct GNUNET_MessageHeader)}, {&handle_list, NULL, GNUNET_MESSAGE_TYPE_ARM_LIST, sizeof (struct GNUNET_MessageHeader)}, {NULL, NULL, 0, 0} }; char *defaultservices; const char *pos; struct ServiceList *sl; cfg = c; server = serv; GNUNET_assert (serv != NULL); GNUNET_SCHEDULER_add_delayed (GNUNET_TIME_UNIT_FOREVER_REL, &shutdown_task, NULL); child_death_task = GNUNET_SCHEDULER_add_read_file (GNUNET_TIME_UNIT_FOREVER_REL, GNUNET_DISK_pipe_handle (sigpipe, GNUNET_DISK_PIPE_END_READ), &maint_child_death, NULL); if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_PREFIX", &prefix_command)) prefix_command = GNUNET_strdup (""); if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "GLOBAL_POSTFIX", &final_option)) final_option = GNUNET_strdup (""); GNUNET_CONFIGURATION_iterate_sections (cfg, &setup_service, NULL); /* start default services... */ if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, "ARM", "DEFAULTSERVICES", &defaultservices)) { GNUNET_log (GNUNET_ERROR_TYPE_INFO, _("Starting default services `%s'\n"), defaultservices); if (0 < strlen (defaultservices)) { for (pos = strtok (defaultservices, " "); NULL != pos; pos = strtok (NULL, " ")) { sl = find_service (pos); if (NULL == sl) { GNUNET_log (GNUNET_ERROR_TYPE_ERROR, _ ("Default service `%s' not configured correctly!\n"), pos); continue; } sl->is_default = GNUNET_YES; start_process (sl); } } GNUNET_free (defaultservices); } else { GNUNET_log (GNUNET_ERROR_TYPE_INFO, _ ("No default services configured, GNUnet will not really start right now.\n")); } /* process client requests */ GNUNET_SERVER_add_handlers (server, handlers); }
int test_waitpid() { test_Data; void* proc; void* proc2; int ret; int status=-1; test_Title("WAITPID"); test_Next("waitpid"); proc = create_process(doafunc, "A", "rw", fids); if (proc) start_process(proc); else perror("Failed to start process A: "); // test return values of calls to waitpid with different options and pid's if (proc) { // test with option WNOHANG and a correct pid on an active process ret = wait_for_process_id(proc,get_proc_id(proc),WNOHANG,&status); test(ret==0); // test with an invalid pid ret = wait_for_process_id(proc,99,0,&status); test(errno==ECHILD&&ret==-1); // test with invalid options ret = wait_for_process_id(proc,99,17,&status); test(errno==EINVAL&&ret==-1); ret = wait_for_process_id(proc,99,18,&status); test(errno==EINVAL&&ret==-1); // process is still active keep waiting until it dies do { ret = wait_for_process_id(proc,get_proc_id(proc),WNOHANG,&status); } while(!WIFEXITED(status)&&ret==0); test(ret==get_proc_id(proc)); printf("child exited, status=%d\n", WEXITSTATUS(status)); } // create another process and test waitpid with pid -1 and options 0 // this is the same as calling wait proc2 = create_process(doafunc, "B", "rw", fids); if (proc2) start_process(proc2); else perror("Failed to start process B: "); if (proc2) { //wait for proc2 to finish do { ret = wait_for_process_id(proc2,-1,0,&status); } while (!WIFEXITED(status)); test(ret==get_proc_id(proc2)); printf("child exited, status=%d\n", WEXITSTATUS(status)); } fflush(stdout); fclose(stdout); test_Close(); return 0; }
/****************************************************************************** * extract_files: extract and restore files from binary. * * @param hwnd: handle to window * ******************************************************************************/ static int extract_files(HWND hwnd) { char *unix_style_work_dir_path, *command = NULL; char *work_dir_path; int command_length = 0; char *pch1, *pch2, *pch3; int i, j; log_message("Base extraction path: %s\n", temp_dir_path); /* Create the path to the work directory */ if (g_user_path == NULL) { work_dir_path = allocate_string_buffer(strlen(temp_dir_path) + strlen(work_dir_basename) + RANDOM_STRING_LEN + strlen(DIRSEPSTR)); if (work_dir_path == NULL) { fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(20); } if (g_env_var_path == NULL) { strcpycat(temp_dir_path, work_dir_basename, work_dir_path); srand(time(NULL)); generate_random_string(work_dir_path, strlen(work_dir_path), RANDOM_STRING_LEN); } else { strcpy(work_dir_path, temp_dir_path); } strcat(work_dir_path, DIRSEPSTR); } else { log_message("User path: %s\n", g_user_path); if (g_user_path[strlen(g_user_path) - 1] != '\\') { work_dir_path = allocate_string_buffer(strlen(g_user_path) + strlen(DIRSEPSTR)); if (work_dir_path == NULL) { fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(21); } strcpycat(g_user_path, DIRSEPSTR, work_dir_path); } else { work_dir_path = g_user_path; } } log_message("Extraction path: %s\n", work_dir_path); /* Create the work directory */ if (!file_exists (work_dir_path)) if (make_path (work_dir_path, 0777) != 0) { log_message("Could not create directory: %s\n", work_dir_path); fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to create directory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(22); } /* Create unix style work dir path */ unix_style_work_dir_path = replace_sub_string(work_dir_path, DIRSEPSTR, "/"); if (unix_style_work_dir_path == NULL) { log_message("Could not allocate memory for directory path\n"); fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(23); } log_message("Extracting bundles ...\n"); /* Process bundles */ for (i = 0; i < P2_SFX_NUM_BUNDLES; i++) { char *installer_dir_path; installer_dir_path = allocate_string_buffer(strlen(work_dir_path) + strlen(bundles[i].path)); if (installer_dir_path == NULL) { fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(24); } /* Create path to file */ strcpycat(work_dir_path, bundles[i].path, installer_dir_path); for (j = 0; j < bundles[i].num_file_descs; j++) { P2_SFX_FILE_DESC *file_desc = &(bundles[i].files[j]); if (write_file_desc(file_desc, installer_dir_path)) { fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nPossibly check available disk space.\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(25); } } free(installer_dir_path); /* Process commands */ for (j = 0; j < bundles[i].num_commands; j++) { char *setupexe; setupexe = NULL; /* Check to see if command contains setup */ pch3 = strstr(bundles[i].commands[j], SETUP); if (pch3 != NULL) { if (g_console_install == FALSE) { setupexe = replace_sub_string(bundles[i].commands[j], SETUP, GUI_SETUP_COMMAND); } else { setupexe = replace_sub_string(bundles[i].commands[j], SETUP, CONSOLE_SETUP_COMMAND); } } /* If the command contains setup.exe and there is no user path or if it is any other command that doesn't contain setup */ if ((setupexe != NULL && g_user_path == NULL) || setupexe == NULL) { char * tmp; int string_length; /* Substitute windows style path */ if (setupexe == NULL) { pch1 = replace_sub_string(bundles[i].commands[j], WINDOWS_BASE_PATH, work_dir_path); } else { pch1 = replace_sub_string(setupexe, WINDOWS_BASE_PATH, work_dir_path); } if (pch1 == NULL) { log_message("Error: Failed to allocate memory for windows path string\n"); fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(26); } /* Substitute unix style path */ pch2 = replace_sub_string(pch1, UNIX_BASE_PATH, unix_style_work_dir_path); free(pch1); if (pch2 == NULL) { log_message("Error: Failed to allocate memory for unix path string\n"); fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(27); } if (setupexe != NULL) { char * install_once = INSTALL_ONCE; char * install_log = INSTALL_LOG; char * dash_data = DASH_DATA; string_length = strlen(pch2) + strlen(install_once) + strlen(dash_data) + (4 * strlen("\"")) + 1; string_length += strlen(install_log) + strlen(base_log_dir) + strlen(timestamp_log_dir) + 1; tmp = allocate_string_buffer(string_length); if (tmp == NULL) { log_message("Error: Failed to allocate memory for implicit arguments\n"); fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(28); } strcpy(tmp, pch2); strcat(tmp, install_once); strcat(tmp, install_log); strcat(tmp, "\""); strcat(tmp, base_log_dir); strcat(tmp, "\""); strcat(tmp, dash_data); strcat(tmp, "\""); strcat(tmp, timestamp_log_dir); strcat(tmp, "\""); free(pch2); pch2 = tmp; } /* Create command with g_args */ if (setupexe != NULL && g_args != NULL) { string_length = strlen(pch2) + strlen(g_args) + 2; tmp = allocate_string_buffer(string_length); if (tmp == NULL) { log_message("Error: Failed to allocate memory for command with arguments"); fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(29); } strcpy(tmp, pch2); strcat(tmp, " "); strcat(tmp, g_args); free(pch2); pch2 = tmp; } if (setupexe != NULL) { string_length = strlen(pch2) + strlen(VM_ARGS) + strlen(VM_ARG_FILE) + strlen(timestamp_log_dir) + 3; tmp = allocate_string_buffer(string_length); if (tmp == NULL) { log_message("Error: Failed to allocate memory for vm args"); fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nUnable to allocate memory\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(29); } strcpy(tmp, pch2); strcat(tmp, VM_ARGS); strcat(tmp, "\""); strcat(tmp, timestamp_log_dir); strcat(tmp, VM_ARG_FILE); strcat(tmp, "\""); free(pch2); pch2 = tmp; } /* Execute command */ log_message("Executing command: %s\n", pch2); if (setupexe == NULL) { /* All non-setup commands use CreateProcess */ if(start_process(pch2)) { log_message("Error: Failed to execute %s\n", pch2); fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nCommand failure\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(30); } } else { /* Split the command into a "command" and "argument" format */ char * exestring = allocate_string_buffer(strlen(pch2)); char * cmdargs = allocate_string_buffer(strlen(pch2)); HINSTANCE return_value; tmp = strstr(pch2, ".exe"); tmp += (strlen(".exe") + 1); strncpy(exestring, pch2, strlen(pch2) - strlen(tmp)); exestring[strlen(pch2) - strlen(tmp)] = 0; strcpy(cmdargs, tmp); log_message("Installer command = %s\n", exestring); log_message("Installer arguments = %s\n", cmdargs); return_value = ShellExecute(NULL, "open", exestring, cmdargs, NULL, SW_SHOWNORMAL); if ((int)return_value <= 32) { log_message("Error: ShellExecute returned a value of %d\n", (int)return_value); fclose(g_logFile); if (g_console_install == FALSE || g_nosplash == FALSE) { sprintf(msg_box_string, "%s%s%s", "Error extracting files\nCommand failure\n\n", "See the log file at:\n\n", sfx_log_file); MessageBox(hwnd, msg_box_string, NULL, MB_OK); SendMessage(hwnd, WM_DESTROY, 0, 0); } exit(31); } } free(pch2); } } } if (g_console_install == FALSE || g_nosplash == FALSE) { SendMessage(hwnd, WM_DESTROY, 0, 0); } return 0; }
void start_follow() { start_process(follow()); }
void switch_process(process *p) { start_process(p); //_load_TR(); //////print("~~Process started with pid = %d ~~",current_running_process->pid); }
static bool do_change_version(atrt_config& config, SqlResultSet& command, AtrtClient& atrtdb){ /** * TODO make option to restart "not" initial */ uint process_id= command.columnAsInt("process_id"); const char* process_args= command.column("process_args"); g_logger.info("Change version for process: %d, args: %s", process_id, process_args); // Get the process if (process_id > config.m_processes.size()){ g_logger.critical("Invalid process id %d", process_id); return false; } atrt_process& proc= *config.m_processes[process_id]; const char* new_prefix= g_prefix1 ? g_prefix1 : g_prefix; const char* old_prefix= g_prefix; const char *start= strstr(proc.m_proc.m_path.c_str(), old_prefix); if (!start){ /* Process path does not contain old prefix. * Perhaps it contains the new prefix - e.g. is already * upgraded? */ if (strstr(proc.m_proc.m_path.c_str(), new_prefix)) { /* Process is already upgraded, *assume* that this * is ok * Alternatives could be - error, or downgrade. */ g_logger.info("Process already upgraded"); return true; } g_logger.critical("Could not find '%s' in '%s'", old_prefix, proc.m_proc.m_path.c_str()); return false; } // Save current proc state if (proc.m_save.m_saved == false) { proc.m_save.m_proc= proc.m_proc; proc.m_save.m_saved= true; } g_logger.info("stopping process..."); if (!stop_process(proc)) return false; BaseString newEnv = set_env_var(proc.m_proc.m_env, BaseString("MYSQL_BASE_DIR"), BaseString(new_prefix)); proc.m_proc.m_env.assign(newEnv); ssize_t pos = proc.m_proc.m_path.lastIndexOf('/') + 1; BaseString exename(proc.m_proc.m_path.substr(pos)); char * exe = find_bin_path(new_prefix, exename.c_str()); proc.m_proc.m_path = exe; if (exe) { free(exe); } if (process_args && strlen(process_args)) { /* Beware too long args */ proc.m_proc.m_args.append(" "); proc.m_proc.m_args.append(process_args); } { /** * In 5.5...binaries aren't compiled with rpath * So we need an explicit LD_LIBRARY_PATH * So when upgrading..we need to change LD_LIBRARY_PATH * So I hate 5.5... */ #if defined(__MACH__) ssize_t p0 = proc.m_proc.m_env.indexOf(" DYLD_LIBRARY_PATH="); #else ssize_t p0 = proc.m_proc.m_env.indexOf(" LD_LIBRARY_PATH="); #endif ssize_t p1 = proc.m_proc.m_env.indexOf(' ', p0 + 1); BaseString part0 = proc.m_proc.m_env.substr(0, p0); BaseString part1 = proc.m_proc.m_env.substr(p1); proc.m_proc.m_env.assfmt("%s%s", part0.c_str(), part1.c_str()); BaseString lib(g_libmysqlclient_so_path); ssize_t pos = lib.lastIndexOf('/') + 1; BaseString libname(lib.substr(pos)); char * exe = find_bin_path(new_prefix, libname.c_str()); char * dir = dirname(exe); #if defined(__MACH__) proc.m_proc.m_env.appfmt(" DYLD_LIBRARY_PATH=%s", dir); #else proc.m_proc.m_env.appfmt(" LD_LIBRARY_PATH=%s", dir); #endif free(exe); free(dir); } ndbout << proc << endl; g_logger.info("starting process..."); if (!start_process(proc)) return false; return true; }
int main() { start_process(&a, 'a', delay_process[0]); start_process(&b, 'b', delay_process[1]); wait_process(a, 'a'); wait_process(b, 'b'); start_process(&c, 'c', delay_process[2]); start_process(&d, 'd', delay_process[3]); start_process(&e, 'e', delay_process[4]); wait_process(e, 'e'); start_process(&f, 'f', delay_process[5]); start_process(&g, 'g', delay_process[6]); wait_process(g, 'g'); start_process(&h, 'h', delay_process[7]); wait_process(c, 'c'); wait_process(h, 'h'); start_process(&i, 'i', delay_process[8]); wait_process(d, 'd'); wait_process(i, 'i'); start_process(&j, 'j', delay_process[9]); start_process(&k, 'k', delay_process[10]); wait_process(f, 'f'); wait_process(j, 'j'); wait_process(k, 'k'); return 0; }
void wait_for_light(int light_port_) { int l_on_, l_off_, l_mid_, t, OK=0; int p; // temp until tone is implemented float s; while (!OK) { cbc_display_clear(); cbc_printf (0,0,"CALIBRATE: sensor port #%d", light_port_); sleep(1.); beep(); sleep(1.); cbc_printf(0,1," press <-- when light on"); while(!left_button()){/*sensor value when light is on*/ cbc_printf(0,2," value is %d, bright = low ",l_on_=analog10 (light_port_)); msleep(50); } beep(); cbc_printf(0,1," light on value is = %d ", l_on_); sleep(1.); beep(); cbc_printf(0,2," press --> when light off "); while(!right_button()){ /*sensor value when light is off*/ cbc_printf(0,3," value is %d, dark = high ",l_off_=analog10 (light_port_)); msleep(50); } beep(); cbc_printf(0,2," light off value is = %d ", l_off_); sleep(1.); beep(); cbc_printf(0,3," "); if((l_off_-l_on_)>=120){ /*bright = small values */ OK=1; l_mid_=(l_on_+l_off_)/2; cbc_printf(0,4,"Good Calibration!"); cbc_printf(0,6,"Diff = %d: WAITING",l_off_-l_on_); p=start_process(beeper1); while(analog10(light_port_)>l_mid_){ cbc_printf(0,7,"Value = %d; Threshold = %d ",analog10(light_port_),l_mid_); msleep(25); } cbc_printf(0,6,"Going! "); cbc_printf(0,7,"Value = %d; Threshold = %d ",analog10(light_port_),l_mid_); //kill_process(p); //works on cbc __wfl_keep_beeping=0;//avoids kill process which has problems on Mac } else{ s=seconds(); cbc_printf(0,6,"BAD CALIBRATION"); if(l_off_<512){ cbc_printf(0,7," Add Shielding!!"); for(t=0; t<4; t++) {beep(); sleep(.2); beep(); sleep(0.4);} beep(); } else{ cbc_printf(0,7," Aim sensor!!"); for(t=0; t<4; t++) {beep(); sleep(.2); beep(); sleep(0.4);} beep(); } } } }
int main() { create_connect(); init_servo(); //light_it_up(LIGHT_PORT); lightstart(LIGHT_PORT,120.0); create_full(); create_drive_segment(HIGH_SPEED, -150); start_process(set_top); create_drive_arc(HIGH_SPEED, -200, 155); create_drive_segment(HIGH_SPEED, -365); create_drive_arc(HIGH_SPEED, 90, -64); create_drive_segment(HIGH_SPEED, -85); create_cease(); set_top(); align_twall(); grab_top_de(); create_spin_angle(400,-165); create_drive_segment(HIGH_SPEED, -320); //align_wall(); create_stop(); create_sync(); dump_kelp_de(); create_drive_segment(HIGH_SPEED,30);//go away from starting box create_spin_angle(HIGH_SPEED, -78);//turn to gate part 1 create_drive_segment(HIGH_SPEED, 938);//go to gate create_drive_arc(HIGH_SPEED,185,84);//arc to gate //create_drive_time(HIGH_SPEED,1800);//go through the gate /* create_drive_segment(HIGH_SPEED,1470); create_drive_segment(HIGH_SPEED,-100); create_spin_angle(HIGH_SPEED,78); */ create_cease(); create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(2000); create_stop(); create_arc(400,400);//arc to the opponent's mpa msleep(7000L); create_stop();//pause to keep the creat create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(-HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(-HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(-HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(-HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(-HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(-HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(-HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(-HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); create_drive_straight(-HIGH_SPEED);//go onto oppponent's side of board msleep(500); create_stop(); /* create_drive_segment(500,-500);//go past the IC create_drive_arc(320,-250,25);//arc to create_drive_arc(320,250,-8); */ //create_drive_segment(HIGH_SPEED,-750); //create_drive_arc(HIGH_SPEED,100,84); //create_drive_segment(HIGH_SPEED,1300); }
static void command_start(char * token, Channel * c) { int pid = 0; int err = 0; char dir[FILE_PATH_SIZE]; char exe[FILE_PATH_SIZE]; char ** args = NULL; char ** envp = NULL; int args_len = 0; int envp_len = 0; int attach = 0; int selfattach = 0; int pending = 0; ChildProcess * prs = NULL; Trap trap; if (set_trap(&trap)) { json_read_string(&c->inp, dir, sizeof(dir)); if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX); json_read_string(&c->inp, exe, sizeof(exe)); if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX); args = json_read_alloc_string_array(&c->inp, &args_len); if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX); envp = json_read_alloc_string_array(&c->inp, &envp_len); if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX); attach = json_read_boolean(&c->inp); if (read_stream(&c->inp) != 0) exception(ERR_JSON_SYNTAX); if (read_stream(&c->inp) != MARKER_EOM) exception(ERR_JSON_SYNTAX); if (dir[0] != 0 && chdir(dir) < 0) err = errno; if (err == 0 && start_process(c, envp, dir, exe, args, attach, &pid, &selfattach, &prs) < 0) err = errno; if (prs != NULL) { write_process_input(prs); prs->out_struct = read_process_output(prs, prs->out, prs->out_id, sizeof(prs->out_id)); if (prs->out != prs->err) prs->err_struct = read_process_output(prs, prs->err, prs->err_id, sizeof(prs->err_id)); strncpy(prs->name, exe, sizeof(prs->name) - 1); } if (!err) { if (attach) { AttachDoneArgs * data = loc_alloc_zero(sizeof *data); data->c = c; strcpy(data->token, token); pending = context_attach(pid, start_done, data, selfattach) == 0; if (pending) { stream_lock(c); } else { err = errno; loc_free(data); } } else { add_waitpid_process(pid); } } if (!pending) { write_stringz(&c->out, "R"); write_stringz(&c->out, token); write_errno(&c->out, err); if (err || pid == 0) { write_stringz(&c->out, "null"); } else { write_context(&c->out, pid); write_stream(&c->out, 0); } write_stream(&c->out, MARKER_EOM); } clear_trap(&trap); } loc_free(args); loc_free(envp); if (trap.error) exception(trap.error); }
static bool do_change_version(atrt_config& config, SqlResultSet& command, AtrtClient& atrtdb){ /** * TODO make option to restart "not" initial */ uint process_id= command.columnAsInt("process_id"); const char* process_args= command.column("process_args"); g_logger.info("Change version for process: %d, args: %s", process_id, process_args); // Get the process if (process_id > config.m_processes.size()){ g_logger.critical("Invalid process id %d", process_id); return false; } atrt_process& proc= *config.m_processes[process_id]; const char* new_prefix= g_prefix1 ? g_prefix1 : g_prefix; const char* old_prefix= g_prefix; const char *start= strstr(proc.m_proc.m_path.c_str(), old_prefix); if (!start){ /* Process path does not contain old prefix. * Perhaps it contains the new prefix - e.g. is already * upgraded? */ if (strstr(proc.m_proc.m_path.c_str(), new_prefix)) { /* Process is already upgraded, *assume* that this * is ok * Alternatives could be - error, or downgrade. */ g_logger.info("Process already upgraded"); return true; } g_logger.critical("Could not find '%s' in '%s'", old_prefix, proc.m_proc.m_path.c_str()); return false; } // Save current proc state if (proc.m_save.m_saved == false) { proc.m_save.m_proc= proc.m_proc; proc.m_save.m_saved= true; } g_logger.info("stopping process..."); if (!stop_process(proc)) return false; BaseString newEnv = set_env_var(proc.m_proc.m_env, BaseString("MYSQL_BASE_DIR"), BaseString(new_prefix)); proc.m_proc.m_env.assign(newEnv); BaseString suffix(proc.m_proc.m_path.substr(strlen(old_prefix))); proc.m_proc.m_path.assign(new_prefix).append(suffix); if (process_args && strlen(process_args)) { /* Beware too long args */ proc.m_proc.m_args.append(" "); proc.m_proc.m_args.append(process_args); } ndbout << proc << endl; g_logger.info("starting process..."); if (!start_process(proc)) return false; return true; }
void twitch() { start_process(twitch_aux(),1); }
void start_echo() { start_process(sample_sound()); start_process(capture_command(),1); start_process(echo_control(),1); start_process(rpt(),1); }
int entry_point( int argc , char* argv[] ) { if( ! ( 1 < argc ) ){ /* オプションが足りない */ print_help_text(argv[0]); return EXIT_SUCCESS; } /* まず一段階目のfork では SIGCHLD を 無視する */ { struct sigaction sa = {{0}}; sa.sa_handler = SIG_IGN; sa.sa_flags = SA_NOCLDWAIT; if (sigaction(SIGCHLD, &sa, NULL) == -1) { return EXIT_FAILURE; } } { const pid_t pid = fork(); if( pid < 0 ){ // fork fail. perror( "fork faild" ); return EXIT_FAILURE; } if( 0 != pid ){ return EXIT_SUCCESS; } /* セッショングループを作り直して端末グループから外れる */ assert( 0 == pid && "the process is child process."); if( -1 == setsid() ){ perror("create new session"); } } /* パイプを作成する */ int logger_pipes[2] = {-1,-1}; if( pipe( logger_pipes ) ){ perror( "pipe()" ); return EXIT_FAILURE; } assert( 0 <=logger_pipes[0] ); assert( 0 <=logger_pipes[1] ); /* ログを書きだす先の プロセスを作成する */ const pid_t logger_pid = fork(); if( -1 == logger_pid ){ perror( "fork() faild"); VERIFY( 0 == close( logger_pipes[WRITE_SIDE] )); VERIFY( 0 == close( logger_pipes[READ_SIDE] )); abort(); } if( 0 == logger_pid){ VERIFY( 0 == close( logger_pipes[WRITE_SIDE] )); exec_logger_process( logger_pipes[READ_SIDE] ); return EXIT_FAILURE; }else{ VERIFY( 0 == close( logger_pipes[READ_SIDE] )); /* 標準入力を /dev/null に置き換える */ { int null_in = open( "/dev/null" , O_RDONLY ); if( -1 == null_in ){ return EXIT_FAILURE; } int null_out = open( "/dev/null" , O_WRONLY ); if( -1 == null_out ){ return EXIT_FAILURE; } int stdin_dup = dup( STDIN_FILENO ); int stdout_dup = dup( STDOUT_FILENO ); int stderr_dup = dup( STDERR_FILENO ); VERIFY( dup2( null_in , STDIN_FILENO ) == STDIN_FILENO ); VERIFY( dup2( null_out , STDOUT_FILENO ) == STDOUT_FILENO); VERIFY( dup2( null_out , STDERR_FILENO ) == STDERR_FILENO ); VERIFY( 0 == close( stdin_dup ) ); VERIFY( 0 == close( stdout_dup ) ); VERIFY( 0 == close( stderr_dup ) ); VERIFY( 0 == close( null_in )); VERIFY( 0 == close( null_out )); } struct process_param param = { logger_pipes[WRITE_SIDE] ,NULL}; char* pid_file_path = malloc( sizeof(char) * PATH_MAX ); if( pid_file_path ){ // TODO ここの PID_FILE_PATH の作り方、もうちょっと注意が必要 char *p = strrchr( argv[0] , '/' ); if( p ){ p++; p = (('\0' == *p) ? NULL : p); }else{ p = argv[0]; } VERIFY( 0 < snprintf( pid_file_path, sizeof( char ) * PATH_MAX , "/tmp/%s.pid" , (p)?(p): argv[0] ) ); param.pid_file_path = pid_file_path; const size_t params_len = argc; char**params = malloc( sizeof(char*) * params_len ); if( params ){ // params に strdup で引数を積んでいく for( size_t i = 0 ; i < (params_len -1); ++i ){ params[i] = strdup( argv[ i + 1] ); } params[params_len - 1] = NULL; if( EXIT_SUCCESS != start_process(param, params[0], params ) ){ // TODO spawn 失敗した } for( size_t i = 0; i < params_len ; ++i ){ if( params[i] ){ free( params[i] ); } } free( params ); } free( pid_file_path ); } VERIFY( 0 == close( logger_pipes[WRITE_SIDE] )); } return EXIT_SUCCESS; }
/* * Export the function that handles a connection. */ int listener_newthread(SOCKET sock, int port, SOCKADDR_IN remoteaddr) { int len; char *nonce = NULL; doit_ctx *ctx = NULL; char *cmdline = NULL, *currdir = NULL; DWORD threadid; if (secret_reload) load_secret(); ctx = doit_init_ctx(secret, secretlen); if (!ctx) goto done; doit_perturb_nonce(ctx, "server", 6); doit_perturb_nonce(ctx, &remoteaddr, sizeof(remoteaddr)); threadid = GetCurrentThreadId(); doit_perturb_nonce(ctx, &threadid, sizeof(threadid)); nonce = doit_make_nonce(ctx, &len); if (do_send(sock, nonce, len) != len) goto done; free(nonce); nonce = NULL; while (1) { cmdline = do_fetch_line(sock, ctx); if (!cmdline) goto done; if (!strcmp(cmdline, "SetDirectory")) { /* * Read a second line and store it for use as the * default directory of a subsequent CreateProcess or * ShellExecute. */ free(cmdline); cmdline = NULL; cmdline = do_fetch_line(sock, ctx); if (!cmdline) goto done; currdir = cmdline; continue; } if (!strcmp(cmdline, "ShellExecute") || !strcmp(cmdline, "ShellExecuteArgs")) { int ret; int with_args; char *args; /* * Read a second line and feed it to ShellExecute(). Give * back either "+" (meaning OK) or "-" followed by an error * message (meaning not OK). * * ShellExecuteArgs is an alternative form in which we * also provide arguments to the process. */ if (!strcmp(cmdline, "ShellExecuteArgs")) with_args = TRUE; else with_args = FALSE; free(cmdline); cmdline = NULL; cmdline = do_fetch_line(sock, ctx); if (with_args) args = do_fetch_line(sock, ctx); else args = NULL; ret = (int)ShellExecute(listener_hwnd, "open", cmdline, args, currdir, SW_SHOWNORMAL); if (args) free(args); if (ret <= 32) { char *msg = "-ShellExecute failed: unknown error\n"; if (ret == 0) msg = "-ShellExecute failed: Out of memory or resources\n"; if (ret == ERROR_FILE_NOT_FOUND) msg = "-ShellExecute failed: File not found\n"; if (ret == ERROR_PATH_NOT_FOUND) msg = "-ShellExecute failed: Path not found\n"; if (ret == ERROR_BAD_FORMAT) msg = "-ShellExecute failed: Invalid .exe file\n"; if (ret == SE_ERR_ACCESSDENIED) msg = "-ShellExecute failed: Access denied\n"; if (ret == SE_ERR_ASSOCINCOMPLETE) msg = "-ShellExecute failed: File name association incomplete or invalid\n"; if (ret == SE_ERR_DDEBUSY) msg = "-ShellExecute failed: DDE busy\n"; if (ret == SE_ERR_DDEFAIL) msg = "-ShellExecute failed: DDE transaction failed\n"; if (ret == SE_ERR_DDETIMEOUT) msg = "-ShellExecute failed: DDE transaction timed out\n"; if (ret == SE_ERR_DLLNOTFOUND) msg = "-ShellExecute failed: DLL not found\n"; if (ret == SE_ERR_FNF) msg = "-ShellExecute failed: File not found\n"; if (ret == SE_ERR_NOASSOC) msg = "-ShellExecute failed: No application associated with this file type\n"; if (ret == SE_ERR_OOM) msg = "-ShellExecute failed: Out of memory\n"; if (ret == SE_ERR_PNF) msg = "-ShellExecute failed: Path not found\n"; if (ret == SE_ERR_SHARE) msg = "-ShellExecute failed: Sharing violation\n"; do_doit_send_str(sock, ctx, msg); } else { do_doit_send_str(sock, ctx, "+\n"); } free(cmdline); cmdline = NULL; goto done; } if (!strcmp(cmdline, "WriteClipboard")) { /* * Read data until the connection is closed, and write it * to the Windows clipboard. */ int len; char *msg; free(cmdline); cmdline = NULL; cmdline = do_fetch_all(sock, ctx, &len); if (cmdline) { msg = write_clip(cmdline, len); free(cmdline); cmdline = NULL; } else msg = "-error reading input\n"; do_doit_send_str(sock, ctx, msg); goto done; } if (!strcmp(cmdline, "ReadClipboard")) { /* * Read the Windows Clipboard. Give back a 4-byte * length followed by the text, and then send either * "+\n" or "-error message\n". */ int is_err; char *data = read_clip(&is_err); char length[4]; if (is_err) { /* data is an error message */ PUT_32BIT_MSB_FIRST(length, 0); do_doit_send(sock, ctx, length, 4); do_doit_send_str(sock, ctx, data); } else { int len = strlen(data); PUT_32BIT_MSB_FIRST(length, len); do_doit_send(sock, ctx, length, 4); do_doit_send(sock, ctx, data, len); do_doit_send_str(sock, ctx, "+\n"); GlobalUnlock(data); } goto done; } if (!strcmp(cmdline, "CreateProcessNoWait") || !strcmp(cmdline, "CreateProcessWait") || !strcmp(cmdline, "CreateProcessWithOutput")) { /* * Read a second line and feed it to CreateProcess. * Optionally, wait for it to finish, or even send output * back. * * If output is sent back, it is sent as a sequence of * Pascal-style length-prefixed strings (a single byte * followed by that many characters), and finally * terminated by a \0 length byte. After _that_ comes the * error indication, which may be "+number\n" for a * termination with exit code, or "-errmsg\n" if a system * call fails. */ int wait, output; struct process proc; if (!strcmp(cmdline, "CreateProcessNoWait")) wait = output = 0; if (!strcmp(cmdline, "CreateProcessWait")) wait = 1, output = 0; if (!strcmp(cmdline, "CreateProcessWithOutput")) wait = output = 1; free(cmdline); cmdline = NULL; cmdline = do_fetch_line(sock, ctx); proc = start_process(cmdline, wait, output, currdir); if (proc.error) { if (output) do_doit_send(sock, ctx, "\0", 1); do_doit_send_str(sock, ctx, proc.error); goto done; } if (wait) { int err; if (output) { char buf[256]; int len; while ((len = read_process_output(proc, buf+1, sizeof(buf)-1)) > 0) { buf[0] = len; do_doit_send(sock, ctx, buf, len+1); } do_doit_send(sock, ctx, "\0", 1); } err = process_exit_code(proc); if (err < 0) { do_doit_send_str(sock, ctx, "-GetExitCodeProcess failed\n"); } else { char buf[32]; sprintf(buf, "+%d\n", err); do_doit_send_str(sock, ctx, buf); } } else { do_doit_send_str(sock, ctx, "+\n"); } } /* * If we've reached here without `continue' or leaving the * loop, we must have an unrecognised command. */ do_doit_send_str(sock, ctx, "-unrecognised command \""); do_doit_send_str(sock, ctx, cmdline); do_doit_send_str(sock, ctx, "\"\n"); } done: if (nonce) free(nonce); if (cmdline) free(cmdline); if (currdir) free(currdir); if (ctx) doit_free_ctx(ctx); closesocket(sock); return 0; }
/** * Used to launch all the items in a passed in directory location. This function * indicates if a terminal error has occurred, or if the directory is empty with * the return value. * * @param[in] const char *directory: The directory location from which things * need to be luanched. * * @return int: To indicate normal operation, empty directory, or terminal error */ int32_t launch_itemsInDir( const char *directory ) { int32_t rc = 0; int32_t launch_attempts = 0, run_time = 0; struct dirent *dp; bool success = true; bool empty_dir = true; DIR *dir; printf("EXECUTING: Opening directory %s\n", directory); errno = 0; dir = opendir(directory); if (NULL == dir) { syslog(LOG_ERR, "%s:%d ERROR: unable to open dir %s (%d:%s)", __FUNCTION__, __LINE__, directory, errno, strerror(errno)); success = false; } else { printf("SUCCESS: Directory %s opened!\n", directory); printf("EXECUTING: Checking if files are present in directory %s\n", directory); errno = 0; dp = readdir(dir); while ((NULL != dp) && (true == success)) { if ('.' != dp->d_name[0]) { printf("SUCCESS: File found: %s\n", dp->d_name); empty_dir = false; printf("EXECUTING: Putting file path and name together in malloc()'ed area\n"); nth_node->dir = NULL; errno = 0; rc = asprintf(&nth_node->dir, "%s/%s", directory, dp->d_name); if ((0 >= rc) || (NULL == nth_node->dir)) { syslog(LOG_ERR, "%s:%d ERROR: unable to allocate %s/%s (%d: %s)", __FUNCTION__, __LINE__, directory, dp->d_name, errno, strerror(errno)); success = false; } else { printf("SUCCESS: String combination completed\n"); } if (true == success) { printf("EXECUTING: Copying filename\n"); errno = 0; nth_node->item_name = strdup(dp->d_name); if (NULL == nth_node->item_name) { syslog(LOG_ERR, "%s:%d ERROR: unable to dup filename %s (%d: %s)", __FUNCTION__, __LINE__, dp->d_name, errno, strerror(errno)); success = false; } else { printf("SUCCESS: String copying completed\n"); } } if (true == success) { printf("EXECUTING: Allocating space for next item in linked list\n"); errno = 0; nth_node->next = (child_pid_list *)malloc(sizeof(child_pid_list)); if (NULL == nth_node->next) { syslog(LOG_ERR, "%s:%d ERROR: unable to malloc new node (%d: %s)", __FUNCTION__, __LINE__, errno, strerror(errno)); success = false; } else { printf("SUCCESS: Space allocated for next item\n"); } } if (true == success) { printf("EXECUTING: Assigning a 4 character name to item %s\n", nth_node->item_name); assign_procName(nth_node->proc_name, first_node, nth_node); if (true == success) { printf("SUCCESS: Assigned name of %s\n", nth_node->proc_name); syslog(LOG_DEBUG, "SUCCESS: Assigned item_name %s proc_name %s", nth_node->item_name, nth_node->proc_name); } } if (true == success) { printf("EXECUTING: Launching item %s\n", nth_node->dir); success = start_process(nth_node); if (true == success) { printf("SUCCESS: Item launch attempt complete\n"); } } if (true == success) { /* Check if the process just launched was successful, if * not, try up to four times to restart it. The waitpid() * function will return a false positive if the child * process has not yet tried to execl(). The run_time value * is used to make sure that enough time has been given to * make sure that execl() was called. */ launch_attempts = 1; run_time = 0; while ( launch_attempts < MAX_LAUNCH_ATTEMPTS && run_time <= START_ENSURE_DELAY ) { sleep(LAUNCH_CHECK_PERIOD); errno = 0; printf("EXECUTING: Checking status of %s after initial launch\n", nth_node->item_name); nth_node->alive = waitpid(nth_node->child_pid, &rc, WNOHANG); if ( normal != nth_node->alive ) { syslog(LOG_ERR, "ERROR: File launch failed! (%s in %s) (try #%d) (%d:%s)", dp->d_name, directory, launch_attempts, errno, strerror(errno)); printf("ERROR: File %s not launched properly! (%d:%s)\n", dp->d_name, errno, strerror(errno)); start_process(nth_node); launch_attempts++; nth_node->alive = normal; run_time = 0; } else { run_time += LAUNCH_CHECK_PERIOD; } } /* while ( launch_attempts < MAX_LAUNCH_ATTEMPTS && run_time <= START_ENSURE_DELAY ) */ sleep(START_ENSURE_DELAY); errno = 0; nth_node->alive = waitpid(nth_node->child_pid, &rc, WNOHANG); if ( normal != nth_node->alive ) { /* This last launch error needs to be outside the previous for loop in order to * log the error for a fifth launch error. */ syslog(LOG_ERR, "ERROR: File launch failed! (%s in %s) (try #%d) (%d:%s)", dp->d_name, directory, launch_attempts, errno, strerror(errno)); printf("ERROR: File %s not launched properly! (%d:%s)\n", dp->d_name, errno, strerror(errno)); syslog(LOG_ERR, "NOTICE: Process for %s in %s disabled permanently! (%d:%s)", dp->d_name, directory, errno, strerror(errno)); printf("NOTICE: Process for %s in %s disabled permanently! (%d:%s)\n", dp->d_name, directory, errno, strerror(errno)); nth_node->alive = downPermanently; /* return a termination value if it is AACM that failed */ if ( dirs[0] == directory ) { syslog(LOG_ERR, "ERROR: AACM Cannot be started! (%d:%s)", errno, strerror(errno)); printf("ERROR: AACM Cannot be started! (%d:%s)\n", errno, strerror(errno)); success = false; } } /* if ( normal != nth_node->alive ) */ printf("SUCCESS: Status check completed\n"); if ( NULL == nth_node->next ) { syslog(LOG_ERR, "ERROR: In 'realloc()' when adding node to linked list!"); printf("ERROR: In 'realloc()' when adding node to linked list!\n"); success = false; } if (true == success) { printf( "CHILD linked list 'pid': %d\n" , nth_node->child_pid ); printf( "CHILD linked list 'dir': %s\n" , nth_node->dir ); printf( "CHILD linked list 'name': %s\n" , nth_node->item_name ); printf( "this address %p\n" , (void *)nth_node ); printf( "next address %p\n" , (void *)nth_node->next ); } nth_node = nth_node->next; } /* if (true == success) */ printf("EXECUTING: Checking if another file is present in directory %s\n", directory); } /* if ('.' != dp->d_name[0]) */ errno = 0; dp = readdir(dir); } /* while ((NULL != dp) && (true == success)) */ if ((NULL == dp) && (0 != errno)) { syslog(LOG_ERR, "%s:%d ERROR: unable to read dir %s (%d:%s)", __FUNCTION__, __LINE__, directory, errno, strerror(errno)); success = false; } printf("EXECUTING: Leaving directory %s\n", directory); closedir(dir); } /* else ! (NULL == dir) */ if (true != success) { rc = terminalError; } else if ( empty_dir ) { rc = dirIsEmpty; } else { rc = normal; } return rc; } /* int32_t launch_itemsInDir( const char *directory ) */
/** * Move forward, and when a wall is detected, follow it * Last update: - * @version - */ void main() { int ir_current; /* Store, temporarily the ir values */ int ir_previous = 0; int light; /* Initialize all components needed to run the robot */ init_motors(); _motor_initial_speed_ = 100; start_process(running_forever()); while(1) { int enc_dif = _right_enc_counts_-_left_enc_counts_; /* * Depending on the ir_detect() value), * make it rotate, and move forward again */ ir_current = ir_detect(); /* Something is detected */ if(ir_current != 0) { if(ir_current == OBSTACLE_FRONT) { printf("FRONT\n"); /* Stop the robot */ stop_process(_running_process_running_); wait_process(_running_process_running_); /* Check the light difference */ light = light_diff(); rotate(C_MOTOR, ((light < 0) - (light >= 0))*90); /* The robot can go foward after the dodge */ start_process(running_forever()); ir_previous = 0; } else { printf("move out %d\n", 10 * ((ir_previous == OBSTACLE_LEFT) - (ir_previous == OBSTACLE_RIGHT))); /* Stop the robot */ stop_process(_running_process_running_); wait_process(_running_process_running_); rotate(C_MOTOR, 10 * ((ir_current == OBSTACLE_LEFT) - (ir_current == OBSTACLE_RIGHT))); /* The robot can go foward after the dodge */ start_process(running_forever()); ir_previous = ir_current; } } else if(ir_previous) { printf("move to %d\n", -10 * ((ir_previous == OBSTACLE_LEFT) - (ir_previous == OBSTACLE_RIGHT))); /* Stop the robot */ stop_process(_running_process_running_); wait_process(_running_process_running_); /* Check the light difference */ rotate(C_MOTOR, -10 * ((ir_previous == OBSTACLE_LEFT) - (ir_previous == OBSTACLE_RIGHT))); /* The robot can go foward after the dodge */ start_process(running_forever()); } sleep(0.1); } }
int main(int argc, char *argv[]) { // These are all the signals we are likely to get // The shell handles stop/cont signal(SIGTERM, stop_process); signal(SIGINT, stop_process); signal(SIGQUIT, stop_process); signal(SIGABRT, stop_process); workdir = make_path(ZString(strings::really_construct_from_a_pointer, getenv("HOME"), nullptr), "tmwserver"); ZString config = CONFIG; if (argc > 1) config = ZString(strings::really_construct_from_a_pointer, argv[1], nullptr); read_config(config); if (chdir(workdir.c_str()) < 0) { perror("Failed to change directory"); exit(1); } PRINTF("Starting:\n"); PRINTF("* workdir: %s\n", workdir); PRINTF("* login_server: %s\n", login_server); PRINTF("* map_server: %s\n", map_server); PRINTF("* char_server: %s\n", char_server); { //make sure all possible file descriptors are free for use by the servers //if there are file descriptors higher than the max open from before the limit dropped, that's not our problem int fd = sysconf(_SC_OPEN_MAX); while (--fd > 2) if (close(fd) == 0) FPRINTF(stderr, "close fd %d\n", fd); fd = open("/dev/null", O_RDWR); if (fd < 0) { perror("open /dev/null"); exit(1); } dup2(fd, 0); dup2(fd, 1); close(fd); } while (1) { // write stuff to stderr timestamp_seconds_buffer timestamp; stamp_time(timestamp); if (!pid_login) { pid_login = start_process(login_server); FPRINTF(stderr, "[%s] forked login server: %lu\n", timestamp, static_cast<unsigned long>(pid_login)); } if (!pid_char) { pid_char = start_process(char_server); FPRINTF(stderr, "[%s] forked char server: %lu\n", timestamp, static_cast<unsigned long>(pid_char)); } if (!pid_map) { pid_map = start_process(map_server); FPRINTF(stderr, "[%s] forked map server: %lu\n", timestamp, static_cast<unsigned long>(pid_map)); } pid_t dead = wait(NULL); if (dead == -1) { perror("Failed to wait for child"); exit(1); } if (pid_login == dead) pid_login = 0; if (pid_char == dead) pid_char = 0; if (pid_map == dead) pid_map = 0; } }
int main( int argc , char *argv[] ) { if( argc == 1 ) { usage(); exit(0); } argv++; argc--; /* 启动服务 */ if (strcmp(*argv, "start") == 0) { argv++; argc--; start_process(argc, argv); } else if (strcmp(*argv, "add") == 0) { /* 新增服务 */ argv++; argc--; add_process(argc, argv); } else if (strcmp(*argv, "reload") == 0) { /* 重载服务 */ argv++; argc--; mod_process(argc, argv); } else if (strcmp(*argv, "close") == 0) { /* 关闭服务 */ argv++; argc--; stop_process(argc, argv); } else if (strcmp(*argv, "force") == 0) { /* 关闭服务 */ argv++; argc--; force_stop_process(argc, argv); } else if (strcmp(*argv, "view") == 0) { /* 查看服务 */ argv++; argc--; view_process(argc, argv); } else if (strcmp(*argv, "stop") == 0) { /* 停止服务 */ argv++; argc--; close_process(argc, argv); } else { printf("无效的参数:%s\n", *argv); usage(); } return 0; }
static void command_launch(char * token, Channel * c) { int err = 0; char encoding[TERM_PROP_DEF_SIZE]; char pty_type[TERM_PROP_DEF_SIZE]; const char * args[] = TERM_LAUNCH_ARGS; const char * exec = TERM_LAUNCH_EXEC; int selfattach = 0; ProcessStartParams prms; Terminal * term = (Terminal *)loc_alloc_zero(sizeof(Terminal)); memset(&prms, 0, sizeof(prms)); json_read_string(&c->inp, pty_type, sizeof(pty_type)); json_test_char(&c->inp, MARKER_EOA); json_read_string(&c->inp, encoding, sizeof(encoding)); json_test_char(&c->inp, MARKER_EOA); prms.envp = read_env(&c->inp); json_test_char(&c->inp, MARKER_EOM); #if !defined(_WIN32) && !defined(__CYGWIN__) { struct stat st; if (err == 0 && stat(exec, &st) != 0) { err = errno; if (err == ENOENT) { static char fnm[FILE_PATH_SIZE]; /* On some systems (e.g. Free DSB) bash is installed under /usr/local */ assert(exec[0] == '/'); snprintf(fnm, sizeof(fnm), "/usr/local%s", exec); if (stat(fnm, &st) == 0) { args[0] = exec = fnm; err = 0; } } if (err == ENOENT && strcmp(exec, "/bin/bash") == 0) { /* "bash" not found, try "sh" */ const char * fnm = "/bin/sh"; if (stat(fnm, &st) == 0) { args[0] = exec = fnm; err = 0; } } if (err) err = set_fmt_errno(err, "Cannot start %s", exec); } } set_terminal_env(&prms.envp, pty_type, encoding, exec); prms.dir = getenv("HOME"); if (prms.dir) prms.dir = tmp_strdup(prms.dir); #else { const char * home_drv = getenv("HOMEDRIVE"); const char * home_dir = getenv("HOMEPATH"); if (home_drv && home_dir) { prms.dir = tmp_strdup2(home_drv, home_dir); } } #endif prms.exe = exec; prms.args = (char **)args; prms.service = TERMINALS; prms.use_terminal = 1; prms.exit_cb = terminal_exited; prms.exit_args = term; if (err == 0 && start_process(c, &prms, &selfattach, &term->prs) < 0) err = errno; if (!err) { term->bcg = c->bcg; channel_lock_with_msg(term->channel = c, TERMINALS); strlcpy(term->pty_type, pty_type, sizeof(term->pty_type)); strlcpy(term->encoding, encoding, sizeof(term->encoding)); list_add_first(&term->link, &terms_list); assert(find_terminal(get_process_pid(term->prs)) == term); } else { assert(term->prs == NULL); loc_free(term); } /* write result back */ write_stringz(&c->out, "R"); write_stringz(&c->out, token); write_errno(&c->out, err); if (err) { write_stringz(&c->out, "null"); } else { write_context(&c->out, get_process_pid(term->prs)); write_stream(&c->out, 0); } write_stream(&c->out, MARKER_EOM); }
int main(int argc, char **argv) { int rc; pid_t pid; int i; options_t *opts = get_options(argc, argv); char *fullname = NULL; asprintf(&fullname, "%s:", opts->name ? opts->name : argv[0]); argv[0] = fullname; if(opts->detached) { pid = fork(); if(pid == 0) { rc = setsid(); if(rc == -1) { perror("setsid"); return EXIT_FAILURE; } } else if(pid == -1) { perror("fork"); return EXIT_FAILURE; } else { return EXIT_SUCCESS; } } if(opts->group) { struct group *grp = getgrnam(opts->group); if(grp == NULL) { fprintf(stderr, "getgrnam(%s): Couldn't find group\n", opts->group); return EXIT_FAILURE; } rc = setgid(grp->gr_gid); if(rc != 0) { fprintf(stderr, "setgid(%d): Couldn't set the group ID\n", grp->gr_gid); return EXIT_FAILURE; } rc = initgroups(opts->group, grp->gr_gid); if(rc == -1) { fprintf(stderr, "initgroups(%s, %d): You must run the program as root\n", opts->group, grp->gr_gid); return EXIT_FAILURE; } } if(opts->user) { struct passwd *pwd = getpwnam(opts->user); if(pwd == NULL) { fprintf(stderr, "getpwnam(%s): Couldn't find user\n", opts->user); return EXIT_FAILURE; } rc = setuid(pwd->pw_uid); if(rc != 0) { fprintf(stderr, "setuid(%d): Couldn't set the user ID\n", pwd->pw_uid); return EXIT_FAILURE; } } char **versions; numver = get_versions(opts->dir, &versions); pids = (pid_t*)calloc(numver, sizeof(pid_t)); for(i = 0; i < numver; i++) { pid = fork(); switch(pid) { case -1: perror("fork"); kill_processes(SIGTERM); return EXIT_FAILURE; case 0: rc = start_process(opts, versions[i]); if(rc == -1) { /* This is in a child process that might have a "smaller" version of the * list of PIDs. Some processes might then not be killed here. * This is probably good enough corresponding the scope of this program. */ kill_processes(SIGTERM); return EXIT_FAILURE; } default: pids[i] = pid; } } init_sighandler(); asprintf(&argv[1], "%i/%i remaining processes", numver, numver); argv[2] = NULL; int status; while((pid = wait(&status)) != -1 || errno == EINTR) { if(WIFEXITED(status) || WIFSIGNALED(status)) { int nrem = 0; for(i = 0; i < numver; i++) { if(pids[i] == pid) { pids[i] = 0; } if(pids[i] != 0) { nrem++; } } asprintf(&argv[1], "%i/%i remaining processes", nrem, numver); if(nrem == 0) { break; } } } free(fullname); free_options(opts); return EXIT_SUCCESS; }