int UNIX_ONLY(main)VMS_ONLY(dbcertify)(int argc, char **argv) { DCL_THREADGBL_ACCESS; /* Initialization of scaffolding we run on */ GTM_THREADGBL_INIT; gtm_imagetype_init(DBCERTIFY_IMAGE); gtm_env_init(); gtm_utf8_mode = FALSE; /* Only ever runs in V4 database so NO utf8 mode -- ever */ psa_gbl = malloc(SIZEOF(*psa_gbl)); memset(psa_gbl, 0, SIZEOF(*psa_gbl)); UNIX_ONLY(err_init(dbcertify_base_ch)); UNIX_ONLY(sig_init(dbcertify_signal_handler, dbcertify_signal_handler, NULL)); VMS_ONLY(util_out_open(0)); VMS_ONLY(SET_EXIT_HANDLER(exi_blk, dbcertify_exit_handler, exi_condition)); /* Establish exit handler */ VMS_ONLY(ESTABLISH(dbcertify_base_ch)); process_id = getpid(); /* Structure checks .. */ assert((24 * 1024) == SIZEOF(v15_sgmnt_data)); /* Verify V4 file header hasn't suddenly increased for some odd reason */ /* Platform dependent method to get the option scan going and invoke necessary driver routine */ dbcertify_parse_and_dispatch(argc, argv); return SS_NORMAL; }
int do_the_work() { if (dstate_dofork(gDaemonState)) daemonize(); sig_init(); pid_file_init(gPidFileName); msg_note("-- NHT Login Daemon version %s started --\n", gDaemonVersion); while (dstate_active(gDaemonState)) { msg_note("Starting keepalive session with timeout interval of %d\n", gEventTimeout); if (run_keepalive()) sleep(5); /* don't zap all the processor's time */ } msg_note("-- HNT Login Daemon version %s finished --\n", gDaemonVersion); pid_file_cleanup(gPidFileName); sig_cleanup(); return 0; }
int main(int argc, char *argv[]) { DCL_THREADGBL_ACCESS; GTM_THREADGBL_INIT; set_blocksig(); gtm_imagetype_init(DSE_IMAGE); gtm_wcswidth_fnptr = gtm_wcswidth; gtm_env_init(); /* read in all environment variables */ licensed = TRUE; TREF(transform) = TRUE; op_open_ptr = op_open; patch_curr_blk = get_dir_root(); err_init(util_base_ch); GTM_ICU_INIT_IF_NEEDED; /* Note: should be invoked after err_init (since it may error out) and before CLI parsing */ sig_init(generic_signal_handler, dse_ctrlc_handler, suspsigs_handler); atexit(util_exit_handler); SET_LATCH_GLOBAL(&defer_latch, LOCK_AVAILABLE); get_page_size(); stp_init(STP_INITSIZE); rts_stringpool = stringpool; getjobname(); INVOKE_INIT_SECSHR_ADDRS; getzdir(); prealloc_gt_timers(); initialize_pattern_table(); gvinit(); region_init(FALSE); INIT_GBL_ROOT(); /* Needed for GVT initialization */ getjobnum(); util_out_print("!/File !_!AD", TRUE, DB_LEN_STR(gv_cur_region)); util_out_print("Region!_!AD!/", TRUE, REG_LEN_STR(gv_cur_region)); cli_lex_setup(argc, argv); CREATE_DUMMY_GBLDIR(gd_header, original_header, gv_cur_region, gd_map, gd_map_top); gtm_chk_dist(argv[0]); # ifdef DEBUG if ((gtm_white_box_test_case_enabled && (WBTEST_SEMTOOLONG_STACK_TRACE == gtm_white_box_test_case_number) )) { sgmnt_addrs * csa; node_local_ptr_t cnl; csa = &FILE_INFO(gv_cur_region)->s_addrs; cnl = csa->nl; cnl->wbox_test_seq_num = 1; /*Signal the first step and wait here*/ while (2 != cnl->wbox_test_seq_num) /*Wait for another process to get hold of the semaphore and signal next step*/ LONG_SLEEP(10); } # endif if (argc < 2) display_prompt(); io_init(TRUE); while (1) { if (!dse_process(argc)) break; display_prompt(); } dse_exit(); REVERT; }
static void john_init(char *name, int argc, char **argv) { int make_check = (argc == 2 && !strcmp(argv[1], "--make_check")); if (make_check) argv[1] = "--test=0"; #if CPU_DETECT if (!CPU_detect()) { #if CPU_REQ #if CPU_FALLBACK #if defined(__DJGPP__) || defined(__CYGWIN32__) #error CPU_FALLBACK is incompatible with the current DOS and Win32 code #endif if (!make_check) { #define CPU_FALLBACK_PATHNAME JOHN_SYSTEMWIDE_EXEC "/" CPU_FALLBACK_BINARY execv(CPU_FALLBACK_PATHNAME, argv); perror("execv: " CPU_FALLBACK_PATHNAME); } #endif fprintf(stderr, "Sorry, %s is required\n", CPU_NAME); if (make_check) exit(0); error(); #endif } #endif if (!make_check) { path_init(argv); status_init(NULL, 1); opt_init(name, argc, argv); if (options.flags & FLG_CONFIG_CLI) { cfg_init(options.config, 1); cfg_init(CFG_ALT_NAME, 0); } else { #if JOHN_SYSTEMWIDE cfg_init(CFG_PRIVATE_FULL_NAME, 1); cfg_init(CFG_PRIVATE_ALT_NAME, 1); #endif cfg_init(CFG_FULL_NAME, 1); cfg_init(CFG_ALT_NAME, 0); } } john_register_all(); common_init(); sig_init(); john_load(); }
int uu_create_process( int ppid ) { hal_mutex_lock(&proc_lock); uuprocess_t *p = get_proc(); assert(p); memset( p, 0, sizeof(uuprocess_t) ); p->pid = get_pid(); p->ppid = p->pid; p->pgrp_pid = p->pid; p->sess_pid = p->pid; p->uid = p->euid = p->gid = p->egid = 0; // Let it be root at start p->umask = 0664; int i; for( i = 0; i < MAX_UU_TID; i++ ) p->tids[i] = -1; uuprocess_t * parent = proc_by_pid(ppid); if( parent ) { p->ppid = ppid; p->pgrp_pid = parent->pgrp_pid; p->sess_pid = parent->sess_pid; p->ctty = parent->ctty; p->cwd_file = copy_uufile( parent->cwd_file ); memcpy( p->cwd_path, parent->cwd_path, FS_MAX_PATH_LEN ); p->umask = parent->umask; } else { //reopen_stdioe( p, "/dev/tty" ); strlcpy( p->cwd_path, "/", FS_MAX_PATH_LEN ); } sig_init( &(p->signals) ); // Mostly created, do final things SHOW_FLOW( 11, "ctty %p", p->ctty ); // allways, while there is no files inherited reopen_stdioe( p, "/dev/tty" ); hal_mutex_unlock(&proc_lock); return p->pid; };
int main(void) { t_options opt_val; t_options *opt = &opt_val; options_init( opt, SR, BS ); t_num *x = sig_init(opt), *y = sig_init(opt); t_phasor phs; dsp_alg_phasor_init( &phs, opt, 0 ); dsp_alg_bias(BS, 441, x, x); dsp_alg_phasor( &phs, x, y ); sig_print( opt, y ); sig_free(x); sig_free(y); return 0; }
main() { sig_init(NULL); (void)printf("\n\n signals handling - test module\n\n"); (void)printf("This program is going to loop until a signal is received.\n"); (void)printf("To perform this test, you can either run this program in background\n"); (void)printf("or send signals from another terminal.\n"); (void)printf("To send a signal, use KILL command with the appropriate signal name:\n"); (void)printf("one of HUP, ILL, TRAP, FPE, BUS, SEGV, INT, QUIT, TERM, ABRT, EMT,\n"); (void)printf(" SYS, PIPE, URG \n"); (void)printf("\nprocess id is : %d\n\n", getpid()); (void)printf("waiting for signal...\n"); for(;;) sleep(1); }
slist_t * parse_fct(ea_t ea, char options) { slist_t * sl; psig_t * sig; func_t * fct; int i, k; pflow_chart_t * fchart; short opcodes[256]; char buf[512]; fct = get_func(ea); if (!fct) return NULL; if (!pget_func_name(ea, buf, sizeof(buf))) return NULL; fchart = new pflow_chart_t(fct); sl = siglist_init(fchart->nproper, NULL); if (!sl) return NULL; for (i=0; i<fchart->nproper; i++) { memset(opcodes, '\0', sizeof(opcodes)); sig = sig_init(); if (!sig) { siglist_free(sl); delete fchart; return NULL; } sig_set_start(sig, fchart->blocks[i].startEA); sig_set_name(sig, buf); for (k=0; k<fchart->nsucc(i); k++) sig_add_sref(sig, fchart->blocks[i].succ[k].ea, fchart->blocks[i].succ[k].type, CHECK_REF); sig_add_block(sig, opcodes, fchart->blocks[i].startEA, fchart->blocks[i].endEA, 1, options); sig_calc_sighash(sig, opcodes, 1); siglist_add(sl, sig); } siglist_sort(sl); delete fchart; return sl; }
int main(int argc, char *argv[]) { /* Get command arguments */ if ( parse_options(argc, argv) ) usage(); if ( devname == NULL ) usage(); if ( opt & CAPTURE_OPT_DEBUG ) { dprintf("START: device=\"%s\" callback(w)=%d update(w)=%d\n", devname, callback_fd, update_fd); } /* Enable multithreading */ if ( !g_thread_supported() ) g_thread_init(NULL); /* Open capture device */ capture = _capture_interface.open(devname, opt, update, NULL); if ( capture == NULL ) { eprintf("Failed to open capture device\n"); exit(1); } callback_open(capture); /* Hook termination procedure at exit stack and signal handling */ atexit(terminate); sig_init(terminate); signal(SIGPIPE, SIG_IGN); /* Hook stdin read handler */ fcntl(STDIN_FILENO, F_SETFL, O_NONBLOCK); stdin_channel = g_io_channel_unix_new(STDIN_FILENO); stdin_tag = g_io_add_watch(stdin_channel, G_IO_IN | G_IO_HUP, (GIOFunc) stdin_read, NULL); /* Create main loop */ loop = g_main_loop_new(NULL, FALSE); /* Enter processing loop */ g_main_loop_run(loop); /* Destroy main loop */ g_main_loop_unref(loop); loop = NULL; terminate(); return 0; }
int main (int argc, char **argv) { int res; DCL_THREADGBL_ACCESS; GTM_THREADGBL_INIT; set_blocksig(); gtm_imagetype_init(MUPIP_IMAGE); invocation_mode = MUMPS_UTILTRIGR; gtm_wcswidth_fnptr = gtm_wcswidth; gtm_env_init(); /* read in all environment variables */ err_init(util_base_ch); UNICODE_ONLY(gtm_strToTitle_ptr = >m_strToTitle); GTM_ICU_INIT_IF_NEEDED; /* Note: should be invoked after err_init (since it may error out) and before CLI parsing */ sig_init(generic_signal_handler, NULL, suspsigs_handler, continue_handler); /* Note: no ^C handler is defined (yet) */ atexit(mupip_exit_handler); licensed = TRUE; in_backup = FALSE; op_open_ptr = mu_op_open; mu_get_term_characterstics(); cli_lex_setup(argc,argv); if (argc < 2) /* Interactive mode */ display_prompt(); /* this call should be after cli_lex_setup() due to S390 A/E conversion */ gtm_chk_dist(argv[0]); INIT_GBL_ROOT(); /* Needed for GVT initialization */ init_gtm(); while (TRUE) { func = 0; if ((res = parse_cmd()) == EOF) break; else if (res) { if (1 < argc) rts_error(VARLSTCNT(4) res, 2, LEN_AND_STR(cli_err_str)); else gtm_putmsg(VARLSTCNT(4) res, 2, LEN_AND_STR(cli_err_str)); } if (func) func(); if (argc > 1) /* Non-interactive mode, exit after command */ break; display_prompt(); } mupip_exit(SS_NORMAL); }
int main(void) { // There are a lot of dependencies in the order of these inits. // Don't change the ordering unless you understand this. // Inits can assume that all memory has been zeroed by either // a hardware reset or a watchdog timer reset. cli(); // system and drivers sys_init(); // system hardware setup - must be first rtc_init(); // real time counter xio_init(); // xmega io subsystem sig_init(); // signal flags st_init(); // stepper subsystem - must precede gpio_init() gpio_init(); // switches and parallel IO pwm_init(); // pulse width modulation drivers - must follow gpio_init() // application structures tg_init(STD_INPUT); // tinyg controller (controller.c) - must be first app init; reqs xio_init() cfg_init(); // config records from eeprom - must be next app init mp_init(); // motion planning subsystem cm_init(); // canonical machine - must follow cfg_init() sp_init(); // spindle PWM and variables // now bring up the interupts and get started PMIC_SetVectorLocationToApplication(); // as opposed to boot ROM PMIC_EnableHighLevel(); // all levels are used, so don't bother to abstract them PMIC_EnableMediumLevel(); PMIC_EnableLowLevel(); sei(); // enable global interrupts rpt_print_system_ready_message();// (LAST) announce system is ready _unit_tests(); // run any unit tests that are enabled tg_canned_startup(); // run any pre-loaded commands while (true) { // if (tg.network == NET_MASTER) { // tg_repeater(); // } else if (tg.network == NET_SLAVE) { // tg_receiver(); // } else { tg_controller(); // NET_STANDALONE // } } }
/* el_init(): * Initialize editline and set default parameters. */ public EditLine * el_init(const char *prog, FILE *fin, FILE *fout, FILE *ferr) { EditLine *el = (EditLine *) el_malloc(sizeof(EditLine)); if (el == NULL) return (NULL); memset(el, 0, sizeof(EditLine)); el->el_infile = fin; el->el_outfile = fout; el->el_errfile = ferr; el->el_infd = fileno(fin); if ((el->el_prog = el_strdup(prog)) == NULL) { el_free(el); return NULL; } /* * Initialize all the modules. Order is important!!! */ el->el_flags = 0; if (term_init(el) == -1) { el_free(el->el_prog); el_free(el); return NULL; } (void) key_init(el); (void) map_init(el); if (tty_init(el) == -1) el->el_flags |= NO_TTY; (void) ch_init(el); (void) search_init(el); (void) hist_init(el); (void) prompt_init(el); (void) sig_init(el); (void) read_init(el); return (el); }
void tg_system_reset(void) { cli(); // These inits are order dependent: _tg_debug_init(); // (0) inits for the debug system sys_init(); // (1) system hardware setup xio_init(); // (2) xmega io subsystem tg_init(STD_INPUT); // (3) tinyg controller (arg is std devices) sig_init(); // (4) signal flags rtc_init(); // (5) real time counter st_init(); // (6) stepper subsystem (must run before gp_init()) gpio_init(); // (7) switches and parallel IO PMIC_EnableMediumLevel();// enable TX interrupts for init reporting sei(); // enable global interrupts cfg_init(); // (8) get config record from eeprom (reqs xio) tg_announce(); // print version string }
/** * @brief Main entry point * @param argc Number of arguments * @param argv Arguments as strings * @return EXIT_SUCCESS */ int main(int argc, char **argv) { char secret[SECRET_MAX]; struct options opts; /* Parse options */ (void) memset(&opts, 0, sizeof(struct options)); parse_args(argc, argv, &opts, secret); /* Initialize signals */ sig_init(); /* Disable stdout buffering */ setbuf(stdout, NULL); /* Start stillepost */ game_main(&opts, secret); return EXIT_SUCCESS; }
int ft_fork_shell(t_env *env) { if (E_PID && (E_PID = fork()) < 0) return (RESET_PUT("fork error", NULL)); E_BUILTIN = 0; if (E_PID) { if (isatty(STDIN_FILENO)) sig_ign(); waitpid(E_PID, &E_RET, 0); if (isatty(STDIN_FILENO)) sig_init(); return (E_RET); } else { sig_dfl(); E_RET = exec_bin(env); exit(E_RET); } }
int main(int argc, char **argv) { fdselect_t fdselect; http_redirect_t server_s, *server=&server_s; struct sockaddr_in addr; sockaddrlen_t addrlen; int i, err=-1; char buf[4096]; do { debug_init(DEBUG_INFO, 0, 0); sock_init(); sig_init(); fdselect_init(&fdselect); getcwd(buf, sizeof(buf)); http_redirect_init(server, &fdselect, buf); server->accept_sock = socket(AF_INET, SOCK_STREAM, 0); assertb_sockerr(server->accept_sock>=0); i = 1; setsockopt(server->accept_sock, SOL_SOCKET, SO_REUSEADDR, (const char*)&i, sizeof(i)); addrlen = iaddr_pack(&addr, INADDR_ANY, 8080); i = bind(server->accept_sock, (struct sockaddr*)&addr, addrlen); assertb_sockerr(i==0); i = listen(server->accept_sock, 5); assertb_sockerr(i==0); i = fdselect_set(server->fdselect, server->accept_sock, FDSELECT_READ, http_redirect_select_accept, server); assertb(i>=0); while(!sig_exited) { fdselect_select(&fdselect, 1); } err = 0; } while(0); return err; }
int main(int argc,char *argv[]) { assert(argc >=3); rain_log_init(); rain_ctx_init(154); char *dir = malloc(1024); getcwd(dir,1024); strcat(dir,"/routine/"); //printf("dir:%s %s %s %s\n",dir,argv[0],argv[1],argv[2]); rain_moudle_init(dir); free(dir); rain_timer_init(); rainRpcInit(); rain_life_queue_init(); rain_message_queue_init(); sig_init(); struct rain_ctx * ctx = rain_ctx_new(0,argv[1],argv[2]); if(ctx == NULL){ exit(-1); } //routine_t rid = rain_ctx_getid(ctx); int len = 4; pthread_t threads[len]; int i; for(i=0; i<len; i++){ pthread_create(&threads[i],NULL,worker,NULL); } timer_loop(NULL); /* pthread_t thread_ev; pthread_create(&thread_ev,NULL,evloop,NULL); for(i=0; i<len; i++){ pthread_join(threads[i],NULL); } pthread_join(thread_ev,NULL);*/ exit(0); }
int main (int argc, char *argv[]) { DCL_THREADGBL_ACCESS; GTM_THREADGBL_INIT; set_blocksig(); gtm_imagetype_init(LKE_IMAGE); gtm_wcswidth_fnptr = gtm_wcswidth; gtm_env_init(); /* read in all environment variables */ licensed = TRUE; err_init(util_base_ch); GTM_ICU_INIT_IF_NEEDED; /* Note: should be invoked after err_init (since it may error out) and before CLI parsing */ sig_init(generic_signal_handler, lke_ctrlc_handler, suspsigs_handler); atexit(util_exit_handler); SET_LATCH_GLOBAL(&defer_latch, LOCK_AVAILABLE); get_page_size(); stp_init(STP_INITSIZE); rts_stringpool = stringpool; getjobname(); INVOKE_INIT_SECSHR_ADDRS; getzdir(); prealloc_gt_timers(); initialize_pattern_table(); gvinit(); region_init(TRUE); getjobnum(); cli_lex_setup(argc, argv); /* this should be after cli_lex_setup() due to S390 A/E conversion */ gtm_chk_dist(argv[0]); while (1) { if (!lke_process(argc) || 2 <= argc) break; } lke_exit(); }
int main() { load_conf(); sig_init(); if( (dbgfd = cap_openfile(capg.save_dbg, CAP_TMP_CAMID, capg.save_dbg_name)) < 0) dbgfd = STDERR_FILENO; // main capture thread, capture/encode/send video data if(capg.mock_enable) Pthread_create(&mock_tid, NULL, mock_main, NULL); else Pthread_create(&cap_tid, NULL, cap_main, NULL); // for communication, listen other process's command Pthread_create(&comm_tid, NULL, comm_main, NULL); // handle signal thread Pthread_create(&sig_tid, NULL, sig_main, NULL); // wait thread over if(capg.mock_enable) Pthread_join(mock_tid, NULL); else Pthread_join(cap_tid, NULL); Pthread_join(comm_tid, NULL); Pthread_join(sig_tid, NULL); cap_closefile(capg.save_dbg, dbgfd); return 0; }
/* * main -- * This is the main loop for the standalone curses editor. */ int main(int argc, char *argv[]) { CL_PRIVATE *clp; GS *gp; size_t rows, cols; int rval; char *ttype; /* Create and initialize the global structure. */ __global_list = gp = gs_init(); /* Create and initialize the CL_PRIVATE structure. */ clp = cl_init(gp); /* * Initialize the terminal information. * * We have to know what terminal it is from the start, since we may * have to use termcap/terminfo to find out how big the screen is. */ if ((ttype = getenv("TERM")) == NULL) ttype = "unknown"; term_init(ttype); /* Add the terminal type to the global structure. */ if ((OG_D_STR(gp, GO_TERM) = OG_STR(gp, GO_TERM) = strdup(ttype)) == NULL) err(1, NULL); /* Figure out how big the screen is. */ if (cl_ssize(NULL, 0, &rows, &cols, NULL)) exit (1); /* Add the rows and columns to the global structure. */ OG_VAL(gp, GO_LINES) = OG_D_VAL(gp, GO_LINES) = rows; OG_VAL(gp, GO_COLUMNS) = OG_D_VAL(gp, GO_COLUMNS) = cols; /* Ex wants stdout to be buffered. */ (void)setvbuf(stdout, NULL, _IOFBF, 0); /* Start catching signals. */ if (sig_init(gp, NULL)) exit (1); /* Run ex/vi. */ rval = editor(gp, argc, argv); /* Clean up signals. */ sig_end(gp); /* Clean up the terminal. */ (void)cl_quit(gp); /* * XXX * Reset the O_MESG option. */ if (clp->tgw != TGW_UNKNOWN) (void)cl_omesg(NULL, clp, clp->tgw == TGW_SET); /* * XXX * Reset the X11 xterm icon/window name. */ if (F_ISSET(clp, CL_RENAME)) { (void)printf(XTERM_RENAME, ttype); (void)fflush(stdout); } /* If a killer signal arrived, pretend we just got it. */ if (clp->killersig) { (void)signal(clp->killersig, SIG_DFL); (void)kill(getpid(), clp->killersig); /* NOTREACHED */ } /* Free the global and CL private areas. */ #if defined(DEBUG) || defined(PURIFY) free(clp); free(gp); #endif exit (rval); }
static void john_init(char *name, int argc, char **argv) { int make_check = (argc == 2 && !strcmp(argv[1], "--make_check")); if (make_check) argv[1] = "--test=0"; CPU_detect_or_fallback(argv, make_check); status_init(NULL, 1); if (argc < 2) john_register_all(); /* for printing by opt_init() */ opt_init(name, argc, argv); if (options.listconf && !strcasecmp(options.listconf, "?")) { puts("inc-modes, rules, externals, ext-filters, ext-filters-only,"); puts("ext-modes, build-info, hidden-options, <conf section name>"); exit(0); } if (options.listconf && !strcasecmp(options.listconf, "hidden-options")) { puts("--list=NAME list configuration, rules, etc"); puts("--mkpc=N force a lower max. keys per crypt"); exit(0); } if (!make_check) { #if defined(_OPENMP) && OMP_FALLBACK #if defined(__DJGPP__) || defined(__CYGWIN32__) #error OMP_FALLBACK is incompatible with the current DOS and Win32 code #endif if (!getenv("JOHN_NO_OMP_FALLBACK") && omp_get_max_threads() <= 1) { #define OMP_FALLBACK_PATHNAME JOHN_SYSTEMWIDE_EXEC "/" OMP_FALLBACK_BINARY execv(OMP_FALLBACK_PATHNAME, argv); perror("execv: " OMP_FALLBACK_PATHNAME); } #endif path_init(argv); if (options.listconf && !strcasecmp(options.listconf, "build-info")) { puts("Version: " JOHN_VERSION); puts("Build: " JOHN_BLD _MP_VERSION); printf("Arch: %d-bit %s\n", ARCH_BITS, ARCH_LITTLE_ENDIAN ? "LE" : "BE"); #if JOHN_SYSTEMWIDE puts("System-wide exec: " JOHN_SYSTEMWIDE_EXEC); puts("System-wide home: " JOHN_SYSTEMWIDE_HOME); puts("Private home: " JOHN_PRIVATE_HOME); #endif printf("$JOHN is %s\n", path_expand("$JOHN/")); puts("Rec file version: " RECOVERY_V); printf("CHARSET_MIN: %d (0x%02x)\n", CHARSET_MIN, CHARSET_MIN); printf("CHARSET_MAX: %d (0x%02x)\n", CHARSET_MAX, CHARSET_MAX); printf("CHARSET_LENGTH: %d\n", CHARSET_LENGTH); #ifdef __GNUC__ printf("gcc version: %d.%d.%d\n", __GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__); #endif #ifdef __ICC printf("icc version: %d\n", __ICC); #endif exit(0); } if (options.flags & FLG_CONFIG_CLI) { path_init_ex(options.config); cfg_init(options.config, 1); cfg_init(CFG_FULL_NAME, 1); cfg_init(CFG_ALT_NAME, 0); } else { #if JOHN_SYSTEMWIDE cfg_init(CFG_PRIVATE_FULL_NAME, 1); cfg_init(CFG_PRIVATE_ALT_NAME, 1); #endif cfg_init(CFG_FULL_NAME, 1); cfg_init(CFG_ALT_NAME, 0); } } if (options.subformat && !strcasecmp(options.subformat, "list")) { dynamic_DISPLAY_ALL_FORMATS(); /* NOTE if we have other 'generics', like sha1, sha2, rc4, ... * then EACH of them should have a DISPLAY_ALL_FORMATS() * function and we can call them here. */ exit(0); } if (options.listconf && !strcasecmp(options.listconf, "inc-modes")) { cfg_print_subsections("Incremental", NULL, NULL); exit(0); } if (options.listconf && !strcasecmp(options.listconf, "rules")) { cfg_print_subsections("List.Rules", NULL, NULL); exit(0); } if (options.listconf && !strcasecmp(options.listconf, "externals")) { cfg_print_subsections("List.External", NULL, NULL); exit(0); } if (options.listconf && !strcasecmp(options.listconf, "ext-filters")) { cfg_print_subsections("List.External", "filter", NULL); exit(0); } if (options.listconf && !strcasecmp(options.listconf, "ext-filters-only")) { cfg_print_subsections("List.External", "filter", "generate"); exit(0); } if (options.listconf && !strcasecmp(options.listconf, "ext-modes")) { cfg_print_subsections("List.External", "generate", NULL); exit(0); } /* Catch-all for any other john.conf section name :-) */ if (options.listconf) { cfg_print_subsections(options.listconf, NULL, NULL); exit(0); } initUnicode(UNICODE_UNICODE); /* Init the unicode system */ john_register_all(); /* maybe restricted to one format by options */ common_init(); sig_init(); john_load(); if (options.encodingStr && options.encodingStr[0]) log_event("- %s input encoding enabled", options.encodingStr); #ifdef CL_VERSION_1_0 if (!options.ocl_platform) if ((options.ocl_platform = cfg_get_param(SECTION_OPTIONS, SUBSECTION_OPENCL, "Platform"))) platform_id = atoi(options.ocl_platform); if (!options.ocl_device) if ((options.ocl_device = cfg_get_param(SECTION_OPTIONS, SUBSECTION_OPENCL, "Device"))) gpu_id = atoi(options.ocl_device); #endif }
/* * main -- * This is the main loop for the standalone curses editor. */ int main(int argc, char *argv[]) { static int reenter; CL_PRIVATE *clp; GS *gp; size_t rows, cols; int rval; char *ttype; #ifdef RUNNING_IP char *ip_arg; char **p_av, **t_av; #endif /* If loaded at 0 and jumping through a NULL pointer, stop. */ if (reenter++) abort(); /* Create and initialize the global structure. */ __global_list = gp = gs_init(argv[0]); /* * Strip out any arguments that vi isn't going to understand. There's * no way to portably call getopt twice, so arguments parsed here must * be removed from the argument list. */ #ifdef RUNNING_IP ip_arg = NULL; for (p_av = t_av = argv;;) { if (*t_av == NULL) { *p_av = NULL; break; } if (!strcmp(*t_av, "--")) { while ((*p_av++ = *t_av++) != NULL); break; } if (!memcmp(*t_av, "-I", sizeof("-I") - 1)) { if (t_av[0][2] != '\0') { ip_arg = t_av[0] + 2; ++t_av; --argc; continue; } if (t_av[1] != NULL) { ip_arg = t_av[1]; t_av += 2; argc -= 2; continue; } } *p_av++ = *t_av++; } /* * If we're being called as an editor library, we're done here, we * get loaded with the curses screen, we don't share much code. */ if (ip_arg != NULL) exit (ip_main(argc, argv, gp, ip_arg)); #endif /* Create and initialize the CL_PRIVATE structure. */ clp = cl_init(gp); /* * Initialize the terminal information. * * We have to know what terminal it is from the start, since we may * have to use termcap/terminfo to find out how big the screen is. */ if ((ttype = getenv("TERM")) == NULL) ttype = "unknown"; term_init(gp->progname, ttype); /* Add the terminal type to the global structure. */ if ((OG_D_STR(gp, GO_TERM) = OG_STR(gp, GO_TERM) = strdup(ttype)) == NULL) perr(gp->progname, NULL); /* Figure out how big the screen is. */ if (cl_ssize(NULL, 0, &rows, &cols, NULL)) exit (1); /* Add the rows and columns to the global structure. */ OG_VAL(gp, GO_LINES) = OG_D_VAL(gp, GO_LINES) = rows; OG_VAL(gp, GO_COLUMNS) = OG_D_VAL(gp, GO_COLUMNS) = cols; /* Ex wants stdout to be buffered. */ (void)setvbuf(stdout, NULL, _IOFBF, 0); /* Start catching signals. */ if (sig_init(gp, NULL)) exit (1); /* Run ex/vi. */ rval = editor(gp, argc, argv); /* Clean up signals. */ sig_end(gp); /* Clean up the terminal. */ (void)cl_quit(gp); /* * XXX * Reset the O_MESG option. */ if (clp->tgw != TGW_UNKNOWN) (void)cl_omesg(NULL, clp, clp->tgw == TGW_SET); /* * XXX * Reset the X11 xterm icon/window name. */ if (F_ISSET(clp, CL_RENAME)) { (void)printf(XTERM_RENAME, ttype); (void)fflush(stdout); } /* If a killer signal arrived, pretend we just got it. */ if (clp->killersig) { (void)signal(clp->killersig, SIG_DFL); (void)kill(getpid(), clp->killersig); /* NOTREACHED */ } /* Free the global and CL private areas. */ #if defined(DEBUG) || defined(PURIFY) || defined(LIBRARY) free(clp); free(gp); #endif exit (rval); }
int main(int ac, char** av) { struct stlinky *st; sig_init(); sl = stlink_open_usb(10, 1); if (sl != NULL) { printf("ST-Linky proof-of-concept terminal :: Created by Necromant for lulz\n"); stlink_version(sl); stlink_enter_swd_mode(sl); printf("chip id: %#x\n", sl->chip_id); printf("core_id: %#x\n", sl->core_id); cortex_m3_cpuid_t cpuid; stlink_cpu_id(sl, &cpuid); printf("cpuid:impl_id = %0#x, variant = %#x\n", cpuid.implementer_id, cpuid.variant); printf("cpuid:part = %#x, rev = %#x\n", cpuid.part, cpuid.revision); stlink_reset(sl); stlink_force_debug(sl); stlink_run(sl); stlink_status(sl); /* wait for device to boot */ /* TODO: Make timeout adjustable via command line */ sleep(1); if(ac == 1){ st = stlinky_detect(sl); }else if(ac == 2){ st = malloc(sizeof(struct stlinky)); st->sl = sl; st->off = (int)strtol(av[1], NULL, 16); printf("using stlinky at 0x%x\n", st->off); stlink_read_mem32(sl, st->off + 4, 4); st->bufsize = (size_t) *(unsigned char*) sl->q_buf; printf("stlinky buffer size 0x%zu \n", st->bufsize); }else{ cleanup(0); } if (st == NULL) { printf("stlinky magic not found in sram :(\n"); cleanup(0); } char* rxbuf = malloc(st->bufsize); char* txbuf = malloc(st->bufsize); size_t tmp; nonblock(1); int fd = fileno(stdin); int saved_flags = fcntl(fd, F_GETFL); fcntl(fd, F_SETFL, saved_flags & ~O_NONBLOCK); printf("Entering interactive terminal. CTRL+C to exit\n\n\n"); while(1) { sig_process(); if (stlinky_canrx(st)) { tmp = stlinky_rx(st, rxbuf); fwrite(rxbuf,tmp,1,stdout); fflush(stdout); } if (kbhit()) { tmp = read(fd, txbuf, st->bufsize); stlinky_tx(st,txbuf,tmp); } } } return 0; }
int main(int argc, char* argv[]) { if (getpid() != 1) return client(argc, argv); /* * Hello world. */ banner(); /* * Initial setup of signals, ignore all until we're up. */ sig_init(); /* * Mount base file system, kernel is assumed to run devtmpfs for /dev */ chdir("/"); umask(0); mount("none", "/proc", "proc", 0, NULL); mount("none", "/proc/bus/usb", "usbfs", 0, NULL); mount("none", "/sys", "sysfs", 0, NULL); mkdir("/dev/pts", 0755); mkdir("/dev/shm", 0755); mount("none", "/dev/pts", "devpts", 0, "gid=5,mode=620"); mount("none", "/dev/shm", "tmpfs", 0, NULL); umask(022); /* * Parse kernel parameters */ parse_kernel_cmdline(); /* * Populate /dev and prepare for runtime events from kernel. */ run_interactive(SETUP_DEVFS, "Populating device tree"); /* * Parse configuration file */ parse_finit_conf(FINIT_CONF); /* * Load plugins. Must run after finit.conf has registered * all services, or service plugins won't have anything to * hook on to. */ print_desc("Loading plugins", NULL); print_result(plugin_load_all(PLUGIN_PATH)); /* * Mount filesystems */ #ifdef REMOUNT_ROOTFS_RW run("/bin/mount -n -o remount,rw /"); #endif #ifdef SYSROOT run(SYSROOT, "/", NULL, MS_MOVE, NULL); #endif _d("Root FS up, calling hooks ..."); plugin_run_hooks(HOOK_ROOTFS_UP); umask(0); run("/bin/mount -na"); run("/sbin/swapon -ea"); umask(0022); /* Cleanup stale files, if any still linger on. */ run_interactive("rm -rf /tmp/* /var/run/* /var/lock/*", "Cleanup temporary directories"); /* Base FS up, enable standard SysV init signals */ sig_setup(); _d("Base FS up, calling hooks ..."); plugin_run_hooks(HOOK_BASEFS_UP); /* * Start all bootstrap tasks, no network available! */ svc_bootstrap(); /* * Network stuff */ /* Setup kernel specific settings, e.g. allow broadcast ping, etc. */ run("/sbin/sysctl -e -p /etc/sysctl.conf >/dev/null"); /* Set initial hostname. */ set_hostname(hostname); ifconfig("lo", "127.0.0.1", "255.0.0.0", 1); if (network) run_interactive(network, "Starting networking: %s", network); umask(022); /* Hooks that rely on loopback, or basic networking being up. */ plugin_run_hooks(HOOK_NETWORK_UP); /* * Start all tasks/services in the configured runlevel */ svc_runlevel(cfglevel); _d("Running svc up hooks ..."); plugin_run_hooks(HOOK_SVC_UP); /* * Run startup scripts in /etc/finit.d/, if any. */ if (rcsd && fisdir(rcsd)) { _d("Running startup scripts in %s ...", rcsd); run_parts(rcsd, NULL); } /* Hooks that should run at the very end */ plugin_run_hooks(HOOK_SYSTEM_UP); /* * Enter main loop to monior /dev/initctl and services */ return run_loop(); }
int main(int argc, char **argv) { time_t now; /* Initialise route, runq and job classes */ now = time(NULL); route_init(NULL, 0); route_register(&rt_filea_method); route_register(&rt_fileov_method); route_register(&rt_stdin_method); route_register(&rt_stdout_method); route_register(&rt_stderr_method); if ( ! elog_init(1, "job test", NULL)) elog_die(FATAL, "didn't initialise elog\n"); sig_init(); callback_init(); runq_init(now); meth_init(); job_init(); /* Test should fail due to incorrect method */ elog_printf(DEBUG, "Expect a complaint! -> "); if (job_add(5, 5, 0, 1, "test1a1", "internal_test", "stdout", "stderr", 100, NULL, "echo \"Hello, world\"") != -1) { elog_die(FATAL, "[1a] Shouldn't be able to add\n"); } /* Single test in five seconds, never to run */ if (job_add(5, 5, 0, 1, "test1a2", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1a] Can't add\n"); } /* Attention: some white box testing */ itree_first(runq_event); if (itree_getkey(runq_event) != now+5) { elog_die(FATAL, "[1a] Queued at an incorrect time\n"); } job_clear(); if (!itree_empty(runq_event) || !itree_empty(runq_tab)) { elog_die(FATAL, "[1a] Trees not emptied. runq_events=%d, runq_tab=%d\n", itree_n(runq_event), itree_n(runq_tab)); } now = time(NULL); /* Two tests both in five seconds, never to run */ if (job_add(5, 5, 0, 1, "test1b1", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1b] Can't add first\n"); } if (job_add(5, 5, 0, 1, "test1b2", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1b] Can't add second\n"); } itree_first(runq_event); if (itree_getkey(runq_event) != now+5) { elog_die(FATAL, "[1b] First queued at an incorrect time\n"); } itree_next(runq_event); if (itree_getkey(runq_event) != now+5) { elog_die(FATAL, "[1b] Second queued at an incorrect time\n"); } job_clear(); if (!itree_empty(runq_event) || !itree_empty(runq_tab)) { elog_die(FATAL, "[1b] Trees not emptied. runq_events=%d, runq_tab=%d\n", itree_n(runq_event), itree_n(runq_tab)); } now = time(NULL); /* Two tests one in five seconds, the other in six, never to run */ if (job_add(6, 6, 0, 1, "test1c1", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1c] Can't add first\n"); } if (job_add(now+5, 5, 0, 1, "test1c2", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1c] Can't add second\n"); } itree_first(runq_event); if (itree_getkey(runq_event) != now+5) { elog_die(FATAL, "[1c] First queued at an incorrect time\n"); } itree_next(runq_event); if (itree_getkey(runq_event) != now+6) { elog_die(FATAL, "[1c] Second queued at an incorrect time\n"); } job_clear(); if (!itree_empty(runq_event) || !itree_empty(runq_tab)) { elog_die(FATAL, "[1c] Trees not emptied. runq_events=%d, runq_tab=%d\n", itree_n(runq_event), itree_n(runq_tab)); } now = time(NULL); /* Continuous single test supposed to start two seconds ago, * next run in three; never to run */ if (job_add(-2, 5, 0, 0, "test1d1", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1d] Can't add\n"); } itree_first(runq_event); if (itree_getkey(runq_event) != now+3) { elog_die(FATAL, "[1d] Event queued at an incorrect time: bad=%d good=%ld\n", itree_getkey(runq_event), now+3); } job_clear(); if (runq_nsched() > 0) { elog_die(FATAL, "[1d] Still active work scheduled. runq_events=%d, " "runq_tab=%d runq_nsched()=%d\n", itree_n(runq_event), itree_n(runq_tab), runq_nsched()); runq_dump(); } now = time(NULL); /* Two continous tests, starting two seconds ago, next next run in four; * never to run */ if (job_add(-2, 6, 0, 0, "test1e1", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1e] Can't add first\n"); } if (job_add(-3, 5, 0, 0, "test1e2", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1e] Can't add second\n"); } itree_first(runq_event); while (((struct runq_work*) itree_get(runq_event))->expired) itree_next(runq_event); if (itree_getkey(runq_event) != now+2) { elog_die(FATAL, "[1e] First queued at an incorrect time\n"); } itree_next(runq_event); while (((struct runq_work*) itree_get(runq_event))->expired) itree_next(runq_event); if (itree_getkey(runq_event) != now+4) { elog_die(FATAL, "[1e] Second queued at an incorrect time\n"); } job_clear(); if (runq_nsched() > 0) { elog_die(FATAL, "[1e] Still active work scheduled. runq_events=%d, " "runq_tab=%d runq_nsched()=%d\n", itree_n(runq_event), itree_n(runq_tab), runq_nsched()); runq_dump(); } now = time(NULL); /* Two 5 run jobs, scheduled to start 10 seconds ago, with periods * of 5 and 6 seconds; never to run */ if (job_add(-10, 6, 0, 5, "test1f1", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1f] Can't add first\n"); } if (job_add(-10, 5, 0, 5, "test1f2", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1f] Can't add second\n"); } itree_first(runq_event); while (((struct runq_work*) itree_get(runq_event))->expired) itree_next(runq_event); if (itree_getkey(runq_event) != now+2) { elog_die(FATAL, "[1f] First queued at an incorrect time\n"); } itree_next(runq_event); while (((struct runq_work*) itree_get(runq_event))->expired) itree_next(runq_event); if (itree_getkey(runq_event) != now+5) { elog_die(FATAL, "[1f] Second queued at an incorrect time\n"); } job_clear(); if (runq_nsched() > 0) { elog_die(FATAL, "[1f] Still active work scheduled. runq_events=%d, " "runq_tab=%d runq_nsched()=%d\n", itree_n(runq_event), itree_n(runq_tab), runq_nsched()); runq_dump(); } now = time(NULL); /* Two 5 run jobs, scheduled to start 100 seconds ago, with periods * of 5 and 6 seconds; they should never be scheduled */ if (job_add(-100, 6, 0, 5, "test1g1", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1g] Can't add first\n"); } if (job_add(-100, 5, 0, 5, "test1g2", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1g] Can't add second\n"); } if (runq_nsched() > 0) { elog_die(FATAL, "[1g] Still active work scheduled. runq_events=%d, " "runq_tab=%d runq_nsched()=%d\n", itree_n(runq_event), itree_n(runq_tab), runq_nsched()); runq_dump(); } job_clear(); now = time(NULL); /* Two five run tests, starting at different times in the past, * five runs each wittth different periods; they should both * run now */ if (job_add(-24, 6, 0, 5, "test1h1", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1h] Can't add first\n"); } if (job_add(-20, 5, 0, 5, "test1h2", "internal_test", "stdout", "stderr", 100, "exec", "echo \"Hello, world\"") == -1) { elog_die(FATAL, "[1h] Can't add second\n"); } if (runq_nsched() != 2) { elog_die(FATAL, "[1h] Two jobs should be scheduled not %d\n", runq_nsched()); runq_dump(); } sig_on(); sleep(6); /* let it run */ sleep(1); /* let it run */ sleep(1); /* let it run */ sleep(1); /* let it run */ sig_off(); if (runq_nsched() > 0) { elog_die(FATAL, "[1h] Still active work scheduled. runq_events=%d, " "runq_tab=%d runq_nsched()=%d\n", itree_n(runq_event), itree_n(runq_tab), runq_nsched()); runq_dump(); } job_clear(); #if 0 /* check all tables/lists are empty */ if (!itree_empty(runq_event) || !itree_empty(runq_tab)) { elog_die(FATAL, "[1i] Still entries in tables. runq_events=%d, " "runq_tab=%d runq_nsched()=%d\n", itree_n(runq_event), itree_n(runq_tab), runq_nsched()); runq_dump(); } #endif job_fini(); meth_fini(); runq_fini(); elog_fini(); route_fini(); callback_fini(); printf("%s: tests finished\n", argv[0]); exit(0); }
/* * cl_vi_init -- * Initialize the curses vi screen. */ static int cl_vi_init(SCR *sp) { CL_PRIVATE *clp; char *o_cols, *o_lines, *o_term; const char *ttype; clp = CLP(sp); /* If already initialized, just set the terminal modes. */ if (F_ISSET(clp, CL_SCR_VI_INIT)) goto fast; /* Curses vi always reads from (and writes to) a terminal. */ if (!F_ISSET(clp, CL_STDIN_TTY) || !isatty(STDOUT_FILENO)) { msgq(sp, M_ERR, "016|Vi's standard input and output must be a terminal"); return (1); } /* We'll need a terminal type. */ if (opts_empty(sp, O_TERM, 0)) return (1); ttype = O_STR(sp, O_TERM); /* * XXX * Changing the row/column and terminal values is done by putting them * into the environment, which is then read by curses. What this loses * in ugliness, it makes up for in stupidity. We can't simply put the * values into the environment ourselves, because in the presence of a * kernel mechanism for returning the window size, entering values into * the environment will screw up future screen resizing events, e.g. if * the user enters a :shell command and then resizes their window. So, * if they weren't already in the environment, we make sure to delete * them immediately after setting them. * * XXX * Putting the TERM variable into the environment is necessary, even * though we're using newterm() here. We may be using initscr() as * the underlying function. */ o_term = getenv("TERM"); cl_putenv(sp, "TERM", ttype, 0); o_lines = getenv("LINES"); cl_putenv(sp, "LINES", NULL, (u_long)O_VAL(sp, O_LINES)); o_cols = getenv("COLUMNS"); cl_putenv(sp, "COLUMNS", NULL, (u_long)O_VAL(sp, O_COLUMNS)); /* Delete cur_term if exists. */ if (F_ISSET(clp, CL_SETUPTERM)) { if (del_curterm(cur_term)) return (1); F_CLR(clp, CL_SETUPTERM); } /* * XXX * The SunOS initscr() can't be called twice. Don't even think about * using it. It fails in subtle ways (e.g. select(2) on fileno(stdin) * stops working). (The SVID notes that applications should only call * initscr() once.) * * XXX * The HP/UX newterm doesn't support the NULL first argument, so we * have to specify the terminal type. */ errno = 0; if ((clp->screen = newterm(__UNCONST(ttype), stdout, stdin)) == NULL) { if (errno) msgq(sp, M_SYSERR, "%s", ttype); else msgq(sp, M_ERR, "%s: unknown terminal type", ttype); return (1); } if (o_term == NULL) cl_unsetenv(sp, "TERM"); if (o_lines == NULL) cl_unsetenv(sp, "LINES"); if (o_cols == NULL) cl_unsetenv(sp, "COLUMNS"); /* * XXX * Someone got let out alone without adult supervision -- the SunOS * newterm resets the signal handlers. There's a race, but it's not * worth closing. */ (void)sig_init(sp->gp, sp); /* * We use raw mode. What we want is 8-bit clean, however, signals * and flow control should continue to work. Admittedly, it sounds * like cbreak, but it isn't. Using cbreak() can get you additional * things like IEXTEN, which turns on flags like DISCARD and LNEXT. * * !!! * If raw isn't turning off echo and newlines, something's wrong. * However, it shouldn't hurt. */ noecho(); /* No character echo. */ nonl(); /* No CR/NL translation. */ raw(); /* 8-bit clean. */ idlok(stdscr, 1); /* Use hardware insert/delete line. */ /* Put the cursor keys into application mode. */ (void)keypad(stdscr, TRUE); /* * XXX * The screen TI sequence just got sent. See the comment in * cl_funcs.c:cl_attr(). */ clp->ti_te = TI_SENT; /* * XXX * Historic implementations of curses handled SIGTSTP signals * in one of three ways. They either: * * 1: Set their own handler, regardless. * 2: Did not set a handler if a handler was already installed. * 3: Set their own handler, but then called any previously set * handler after completing their own cleanup. * * We don't try and figure out which behavior is in place, we force * it to SIG_DFL after initializing the curses interface, which means * that curses isn't going to take the signal. Since curses isn't * reentrant (i.e., the whole curses SIGTSTP interface is a fantasy), * we're doing The Right Thing. */ (void)signal(SIGTSTP, SIG_DFL); /* * If flow control was on, turn it back on. Turn signals on. ISIG * turns on VINTR, VQUIT, VDSUSP and VSUSP. The main curses code * already installed a handler for VINTR. We're going to disable the * other three. * * XXX * We want to use ^Y as a vi scrolling command. If the user has the * DSUSP character set to ^Y (common practice) clean it up. As it's * equally possible that the user has VDSUSP set to 'a', we disable * it regardless. It doesn't make much sense to suspend vi at read, * so I don't think anyone will care. Alternatively, we could look * it up in the table of legal command characters and turn it off if * it matches one. VDSUSP wasn't in POSIX 1003.1-1990, so we test for * it. * * XXX * We don't check to see if the user had signals enabled originally. * If they didn't, it's unclear what we're supposed to do here, but * it's also pretty unlikely. */ if (tcgetattr(STDIN_FILENO, &clp->vi_enter)) { msgq(sp, M_SYSERR, "tcgetattr"); goto err; } if (clp->orig.c_iflag & IXON) clp->vi_enter.c_iflag |= IXON; if (clp->orig.c_iflag & IXOFF) clp->vi_enter.c_iflag |= IXOFF; clp->vi_enter.c_lflag |= ISIG; #ifdef VDSUSP clp->vi_enter.c_cc[VDSUSP] = _POSIX_VDISABLE; #endif clp->vi_enter.c_cc[VQUIT] = _POSIX_VDISABLE; clp->vi_enter.c_cc[VSUSP] = _POSIX_VDISABLE; /* * XXX * OSF/1 doesn't turn off the <discard>, <literal-next> or <status> * characters when curses switches into raw mode. It should be OK * to do it explicitly for everyone. */ #ifdef VDISCARD clp->vi_enter.c_cc[VDISCARD] = _POSIX_VDISABLE; #endif #ifdef VLNEXT clp->vi_enter.c_cc[VLNEXT] = _POSIX_VDISABLE; #endif #ifdef VSTATUS clp->vi_enter.c_cc[VSTATUS] = _POSIX_VDISABLE; #endif /* Initialize terminal based information. */ if (cl_term_init(sp)) goto err; fast: /* Set the terminal modes. */ if (tcsetattr(STDIN_FILENO, TCSASOFT | TCSADRAIN, &clp->vi_enter)) { msgq(sp, M_SYSERR, "tcsetattr"); err: (void)cl_vi_end(sp->gp); return (1); } return (0); }
int main( int argc, char **argv ) { //int ret = 0; PTZControlInit(); demo_setting * ext_gSettings = NULL; // Allocate the "global" settings ext_gSettings = (demo_setting*)malloc( sizeof( demo_setting ) ); if ( NULL == ext_gSettings ) { printf( "main::out of memory!\n" ); return -1; } sig_init(); atexit(appExit); //init the setting struct Settings_Initialize( ext_gSettings ); read_Parse(ext_gSettings); //printf("video type = %d \n", ext_gSettings->video_types); //...do your job //close the led setled_off(); //init dma memory akuio_pmem_init(); encode_init(); printf("encode_init ok\n"); //open camera camera_open(ext_gSettings->width, ext_gSettings->height); printf("camera_open ok\n"); //encode_open T_ENC_INPUT encInput; encInput.width = ext_gSettings->width; //实际编码图像的宽度,能被4整除 encInput.height = ext_gSettings->height; //实际编码图像的长度,能被2整除 encInput.kbpsmode = ext_gSettings->kbpsmode; encInput.qpHdr = ext_gSettings->qpHdr; //初始的QP的值 encInput.iqpHdr = ext_gSettings->iqpHdr; //初始的QP的值 encInput.bitPerSecond = ext_gSettings->bitPerSecond; //目标bps encInput.minQp = ext_gSettings->minQp; encInput.maxQp = ext_gSettings->maxQp; encInput.framePerSecond = ext_gSettings->framePerSecond; encInput.video_tytes = ext_gSettings->video_types; encode_open(&encInput); printf("encode_open ok\n"); //set mux mux_input.rec_path = ext_gSettings->rec_path; mux_input.m_MediaRecType = MEDIALIB_REC_AVI_NORMAL; if (ext_gSettings->bhasAudio) { bHasAudio = 1; //mux_input.m_bCaptureAudio = 1; } else { bHasAudio = 0; //mux_input.m_bCaptureAudio = 0; } mux_input.m_bCaptureAudio = 1; //mux video if(parse.format2 == 0) { mux_input.m_eVideoType = MEDIALIB_VIDEO_H264; } else if(parse.format2 == 1) { mux_input.m_eVideoType = MEDIALIB_VIDEO_MJPEG; } mux_input.m_nWidth = parse.width2; mux_input.m_nHeight = parse.height2; //mux audio mux_input.m_eAudioType = MEDIALIB_AUDIO_AAC; mux_input.m_nSampleRate = 8000; //mux_input.abitsrate = ext_gSettings->abitsrate; printf("mux_open ok\n"); //if (ext_gSettings->bhasAudio) { T_AUDIO_INPUT audioInput; audioInput.enc_type = (AUDIO_ENCODE_TYPE_CC)ext_gSettings->audioType; audioInput.nBitsRate = ext_gSettings->abitsrate; audioInput.nBitsPerSample = 16; audioInput.nChannels = 1; audioInput.nSampleRate = ext_gSettings->aSamplerate; audio_open(&audioInput); printf("audio_open ok\n"); audio_start(); } //start ftp server //startFTPSrv(); Init_photograph(); //PTZControlInit(); //start video process video_process_start(); InitMotionDetect(); DemuxForLiveSetCallBack(); TaskScheduler* scheduler = BasicTaskScheduler::createNew(); env = BasicUsageEnvironment::createNew(*scheduler); UserAuthenticationDatabase* authDB = NULL; #ifdef ACCESS_CONTROL // To implement client access control to the RTSP server, do the following: authDB = new UserAuthenticationDatabase; authDB->addUserRecord("username1", "password1"); // replace these with real strings // Repeat the above with each <username>, <password> that you wish to allow // access to the server. #endif // Create the RTSP server: RTSPServer* rtspServer = AKRTSPServer::createNew(*env, RTSPPORT, authDB); if (rtspServer == NULL) { *env << "Failed to create RTSP server: " << env->getResultMsg() << "\n"; appExit(); exit(1); } char const* descriptionString = "Session streamed by \"testOnDemandRTSPServer\""; // Set up each of the possible streams that can be served by the // RTSP server. Each such stream is implemented using a // "ServerMediaSession" object, plus one or more // "ServerMediaSubsession" objects for each audio/video substream. int vsIndex = 0; VIDEO_MODE vm[2] = {VIDEO_MODE_VGA,VIDEO_MODE_VGA}; const char* streamName1 = "vs1"; const char* streamName2 = "vs2"; ((AKRTSPServer*)rtspServer)->SetStreamName(streamName1, streamName2); if(ext_gSettings->video_types == 1) { if(ext_gSettings->width == 640) { vm[0] = VIDEO_MODE_VGA; } else if(ext_gSettings->width == 320) { vm[0] = VIDEO_MODE_QVGA; } else if(ext_gSettings->width == 720) { vm[0] = VIDEO_MODE_D1; } AKIPCMJPEGFramedSource* ipcMJPEGSourcecam = NULL; ServerMediaSession* smsMJPEGcam = ServerMediaSession::createNew(*env, streamName1, 0, descriptionString); AKIPCMJPEGOnDemandMediaSubsession* subsMJPEGcam = AKIPCMJPEGOnDemandMediaSubsession::createNew(*env,ipcMJPEGSourcecam, ext_gSettings->width, ext_gSettings->height, vsIndex); smsMJPEGcam->addSubsession(subsMJPEGcam); subsMJPEGcam->getframefunc = video_process_get_buf; subsMJPEGcam->setledstart = setled_view_start; subsMJPEGcam->setledexit = setled_view_stop; if(bHasAudio) smsMJPEGcam->addSubsession(AKIPCAACAudioOnDemandMediaSubsession::createNew(*env,True,getAACBuf, vsIndex)); rtspServer->addServerMediaSession(smsMJPEGcam); char* url1 = rtspServer->rtspURL(smsMJPEGcam); *env << "using url \"" << url1 <<"\"\n"; delete[] url1; } else if(ext_gSettings->video_types == 0) { if(ext_gSettings->width == 1280) { vm[0] = VIDEO_MODE_720P; } else if(ext_gSettings->width == 640) { vm[0] = VIDEO_MODE_VGA; } else if(ext_gSettings->width == 320) { vm[0] = VIDEO_MODE_QVGA; } else if(ext_gSettings->width == 720) { vm[0] = VIDEO_MODE_D1; } AKIPCH264FramedSource* ipcSourcecam = NULL; ServerMediaSession* smscam = ServerMediaSession::createNew(*env, streamName1, 0, descriptionString); AKIPCH264OnDemandMediaSubsession* subscam = AKIPCH264OnDemandMediaSubsession::createNew(*env,ipcSourcecam, 0, vsIndex); smscam->addSubsession(subscam); if(bHasAudio) smscam->addSubsession(AKIPCAACAudioOnDemandMediaSubsession::createNew(*env,True,getAACBuf, vsIndex)); subscam->getframefunc = video_process_get_buf; subscam->setledstart = setled_view_start; subscam->setledexit = setled_view_stop; rtspServer->addServerMediaSession(smscam); char* url1 = rtspServer->rtspURL(smscam); *env << "using url \"" << url1 <<"\"\n"; delete[] url1; } vsIndex = 1; if(parse.format2 == 0)//264 { if(parse.width2 == 1280) { vm[1] = VIDEO_MODE_720P; } else if(parse.width2 == 640) { vm[1] = VIDEO_MODE_VGA; } else if(parse.width2 == 320) { vm[1] = VIDEO_MODE_QVGA; } else if(parse.width2 == 720) { vm[1] = VIDEO_MODE_D1; } AKIPCH264FramedSource* ipcSourcecam = NULL; ServerMediaSession* smscam = ServerMediaSession::createNew(*env, streamName2, 0, descriptionString); AKIPCH264OnDemandMediaSubsession* subscam = AKIPCH264OnDemandMediaSubsession::createNew(*env,ipcSourcecam, 0, vsIndex); smscam->addSubsession(subscam); if(bHasAudio) smscam->addSubsession(AKIPCAACAudioOnDemandMediaSubsession::createNew(*env,True,getAACBuf, vsIndex)); subscam->getframefunc = video_process_get_buf; subscam->setledstart = setled_view_start; subscam->setledexit = setled_view_stop; rtspServer->addServerMediaSession(smscam); char* url2 = rtspServer->rtspURL(smscam); *env << "using url \"" << url2 <<"\"\n"; delete[] url2; } else if(parse.format2 == 1)//mjpeg { if(parse.width2 == 640) { vm[1] = VIDEO_MODE_VGA; } else if(parse.width2 == 320) { vm[1] = VIDEO_MODE_QVGA; } else if(parse.width2 == 720) { vm[1] = VIDEO_MODE_D1; } AKIPCMJPEGFramedSource* ipcMJPEGSourcecam = NULL; ServerMediaSession* smsMJPEGcam = ServerMediaSession::createNew(*env, streamName2, 0, descriptionString); AKIPCMJPEGOnDemandMediaSubsession* subsMJPEGcam = AKIPCMJPEGOnDemandMediaSubsession::createNew(*env,ipcMJPEGSourcecam, parse.width2, parse.height2, vsIndex); smsMJPEGcam->addSubsession(subsMJPEGcam); subsMJPEGcam->getframefunc = video_process_get_buf; subsMJPEGcam->setledstart = setled_view_start; subsMJPEGcam->setledexit = setled_view_stop; if(bHasAudio) smsMJPEGcam->addSubsession(AKIPCAACAudioOnDemandMediaSubsession::createNew(*env,True,getAACBuf, vsIndex)); rtspServer->addServerMediaSession(smsMJPEGcam); char* url2 = rtspServer->rtspURL(smsMJPEGcam); *env << "using url \"" << url2 <<"\"\n"; delete[] url2; } #if 0 if (rtspServer->setUpTunnelingOverHTTP(80) || rtspServer->setUpTunnelingOverHTTP(8000) || rtspServer->setUpTunnelingOverHTTP(8080)) { *env << "\n(We use port " << rtspServer->httpServerPortNum() << " for optional RTSP-over-HTTP tunneling.)\n"; } else { *env << "\n(RTSP-over-HTTP tunneling is not available.)\n"; } #endif //printf("streamName:%s,Port:%d\n", streamName1, RTSPPORT); NetCtlSrvPar ncsp; memset(&ncsp, 0, sizeof(ncsp)); getDeviceID(ncsp.strDeviceID); printf("device id:**%s**\n", ncsp.strDeviceID); strcpy(ncsp.strStreamName1, streamName1); strcpy(ncsp.strStreamName2, streamName2); ncsp.vm1 = vm[0]; ncsp.vm2 = vm[1]; ncsp.nRtspPort = RTSPPORT; ncsp.nMainFps = parse.fps1; ncsp.nSubFps = parse.fps2; //start net command server startNetCtlServer(&ncsp); printf("[##]start record...\n"); auto_record_file(); printf("[##]auto_record_file() called..\n"); //at last,start rtsp loop env->taskScheduler().doEventLoop(); // does not return return 0; }
int main(int argc, char* argv[]) { char *path; char cmd[256]; int udev = 0; uev_t timer; /* Bootstrap timer, on timeout call finalize() */ uev_ctx_t loop; /* * finit/init/telinit client tool uses /dev/initctl pipe * for compatibility but initctl client tool uses socket */ if (getpid() != 1) return client(argc, argv); /* * Initalize event context. */ uev_init(&loop); ctx = &loop; /* * Set PATH and SHELL early to something sane */ setenv("PATH", _PATH_STDPATH, 1); setenv("SHELL", _PATH_BSHELL, 1); /* * Mount base file system, kernel is assumed to run devtmpfs for /dev */ chdir("/"); umask(0); mount("none", "/proc", "proc", 0, NULL); mount("none", "/sys", "sysfs", 0, NULL); if (fisdir("/proc/bus/usb")) mount("none", "/proc/bus/usb", "usbfs", 0, NULL); /* * Parse kernel command line (debug, rescue, splash, etc.) * Also calls log_init() to set correct log level */ conf_parse_cmdline(); /* Set up canvas */ if (!rescue && !log_is_debug()) screen_init(); /* * In case of emergency. */ emergency_shell(); /* * Initial setup of signals, ignore all until we're up. */ sig_init(); /* * Load plugins early, finit.conf may contain references to * features implemented by plugins. */ plugin_init(&loop); /* * Hello world. */ banner(); /* * Check file filesystems in /etc/fstab */ for (int pass = 1; pass < 10 && !rescue; pass++) { if (fsck(pass)) break; } /* * Initialize .conf system and load static /etc/finit.conf * Also initializes global_rlimit[] for udevd, below. */ conf_init(); /* * Some non-embedded systems without an initramfs may not have /dev mounted yet * If they do, check if system has udevadm and perform cleanup from initramfs */ if (!fismnt("/dev")) mount("udev", "/dev", "devtmpfs", MS_RELATIME, "size=10%,nr_inodes=61156,mode=755"); else if (whichp("udevadm")) run_interactive("udevadm info --cleanup-db", "Cleaning up udev db"); /* Some systems use /dev/pts */ makedir("/dev/pts", 0755); mount("devpts", "/dev/pts", "devpts", 0, "gid=5,mode=620"); /* * Some systems rely on us to both create /dev/shm and, to mount * a tmpfs there. Any system with dbus needs shared memory, so * mount it, unless its already mounted, but not if listed in * the /etc/fstab file already. */ makedir("/dev/shm", 0755); if (!fismnt("/dev/shm") && !ismnt("/etc/fstab", "/dev/shm")) mount("shm", "/dev/shm", "tmpfs", 0, NULL); /* * New tmpfs based /run for volatile runtime data * For details, see http://lwn.net/Articles/436012/ */ if (fisdir("/run") && !fismnt("/run")) mount("tmpfs", "/run", "tmpfs", MS_NODEV, "mode=0755,size=10%"); umask(022); /* Bootstrap conditions, needed for hooks */ cond_init(); /* * Populate /dev and prepare for runtime events from kernel. * Prefer udev if mdev is also available on the system. */ path = which("udevd"); if (!path) path = which("/lib/systemd/systemd-udevd"); if (path) { /* Desktop and server distros usually have a variant of udev */ udev = 1; /* Register udevd as a monitored service */ snprintf(cmd, sizeof(cmd), "[S12345789] pid:udevd %s -- Device event managing daemon", path); if (service_register(SVC_TYPE_SERVICE, cmd, global_rlimit, NULL)) { _pe("Failed registering %s", path); udev = 0; } else { snprintf(cmd, sizeof(cmd), ":1 [S] <svc%s> " "udevadm trigger -c add -t devices " "-- Requesting device events", path); service_register(SVC_TYPE_RUN, cmd, global_rlimit, NULL); snprintf(cmd, sizeof(cmd), ":2 [S] <svc%s> " "udevadm trigger -c add -t subsystems " "-- Requesting subsystem events", path); service_register(SVC_TYPE_RUN, cmd, global_rlimit, NULL); } free(path); } else { path = which("mdev"); if (path) { /* Embedded Linux systems usually have BusyBox mdev */ if (log_is_debug()) touch("/dev/mdev.log"); snprintf(cmd, sizeof(cmd), "%s -s", path); free(path); run_interactive(cmd, "Populating device tree"); } } /* * Start built-in watchdog as soon as possible, if enabled */ wdogpid = watchdog(argv[0]); /* * Mount filesystems */ if (!rescue) { #ifdef REMOUNT_ROOTFS run("mount -n -o remount,rw /"); #endif #ifdef SYSROOT mount(SYSROOT, "/", NULL, MS_MOVE, NULL); #endif } if (!rescue) { _d("Root FS up, calling hooks ..."); plugin_run_hooks(HOOK_ROOTFS_UP); umask(0); if (run_interactive("mount -na", "Mounting filesystems")) plugin_run_hooks(HOOK_MOUNT_ERROR); _d("Calling extra mount hook, after mount -a ..."); plugin_run_hooks(HOOK_MOUNT_POST); run("swapon -ea"); umask(0022); } /* Base FS up, enable standard SysV init signals */ sig_setup(&loop); if (!rescue) { _d("Base FS up, calling hooks ..."); plugin_run_hooks(HOOK_BASEFS_UP); } /* * Set up inotify watcher for /etc/finit.d and read all .conf * files to figure out how to bootstrap the system. */ conf_monitor(&loop); /* * Initalize state machine and start all bootstrap tasks * NOTE: no network available! */ sm_init(&sm); sm_step(&sm); /* Debian has this little script to copy generated rules while the system was read-only */ if (udev && fexist("/lib/udev/udev-finish")) run_interactive("/lib/udev/udev-finish", "Finalizing udev"); /* Start new initctl API responder */ api_init(&loop); umask(022); /* * Wait for all SVC_TYPE_RUNTASK to have completed their work in * [S], or timeout, before calling finalize() */ _d("Starting bootstrap finalize timer ..."); uev_timer_init(&loop, &timer, service_bootstrap_cb, finalize, 1000, 1000); /* * Enter main loop to monior /dev/initctl and services */ _d("Entering main loop ..."); return uev_run(&loop, 0); }
void gtm_startup(struct startup_vector *svec) /* Note: various references to data copied from *svec could profitably be referenced directly */ { unsigned char *mstack_ptr; void gtm_ret_code(); static readonly unsigned char init_break[1] = {'B'}; int4 lct; int i; static char other_mode_buf[] = "OTHER"; mstr log_name; DCL_THREADGBL_ACCESS; SETUP_THREADGBL_ACCESS; assert(INVALID_IMAGE != image_type); assert(svec->argcnt == SIZEOF(*svec)); IA64_ONLY(init_xfer_table()); get_page_size(); cache_table_relobjs = &cache_table_rebuild; ht_rhash_ch = &hashtab_rehash_ch; jbxm_dump_ch = &jobexam_dump_ch; heartbeat_timer_ptr = &heartbeat_timer; stpgc_ch = &stp_gcol_ch; rtn_fst_table = rtn_names = (rtn_tabent *)svec->rtn_start; rtn_names_end = rtn_names_top = (rtn_tabent *)svec->rtn_end; if (svec->user_stack_size < 4096) svec->user_stack_size = 4096; if (svec->user_stack_size > 8388608) svec->user_stack_size = 8388608; mstack_ptr = (unsigned char *)malloc(svec->user_stack_size); msp = stackbase = mstack_ptr + svec->user_stack_size - mvs_size[MVST_STORIG]; /* mark the stack base so that if error occur during call-in gtm_init(), the unwind * logic in gtmci_ch() will get rid of the stack completely */ fgncal_stack = stackbase; mv_chain = (mv_stent *)msp; mv_chain->mv_st_type = MVST_STORIG; /* Initialize first (anchor) mv_stent so doesn't do anything */ mv_chain->mv_st_next = 0; mv_chain->mv_st_cont.mvs_storig = 0; stacktop = mstack_ptr + 2 * mvs_size[MVST_NTAB]; stackwarn = stacktop + (16 * 1024); break_message_mask = svec->break_message_mask; if (svec->user_strpl_size < STP_INITSIZE) svec->user_strpl_size = STP_INITSIZE; else if (svec->user_strpl_size > STP_MAXINITSIZE) svec->user_strpl_size = STP_MAXINITSIZE; stp_init(svec->user_strpl_size); if (svec->user_indrcache_size > MAX_INDIRECTION_NESTING || svec->user_indrcache_size < MIN_INDIRECTION_NESTING) svec->user_indrcache_size = MIN_INDIRECTION_NESTING; TREF(ind_result_array) = (mval **)malloc(SIZEOF(mval *) * svec->user_indrcache_size); TREF(ind_source_array) = (mval **)malloc(SIZEOF(mval *) * svec->user_indrcache_size); TREF(ind_result_sp) = TREF(ind_result_array); TREF(ind_result_top) = TREF(ind_result_sp) + svec->user_indrcache_size; TREF(ind_source_sp) = TREF(ind_source_array); TREF(ind_source_top) = TREF(ind_source_sp) + svec->user_indrcache_size; rts_stringpool = stringpool; TREF(compile_time) = FALSE; /* assert that is_replicator and run_time is properly set by gtm_imagetype_init invoked at process entry */ # ifdef DEBUG switch (image_type) { case GTM_IMAGE: case GTM_SVC_DAL_IMAGE: assert(is_replicator && run_time); break; case MUPIP_IMAGE: assert(!is_replicator && !run_time); break; default: assert(FALSE); } # endif gtm_utf8_init(); /* Initialize the runtime for Unicode */ /* Initialize alignment requirement for the runtime stringpool */ log_name.addr = DISABLE_ALIGN_STRINGS; log_name.len = STR_LIT_LEN(DISABLE_ALIGN_STRINGS); /* mstr_native_align = logical_truth_value(&log_name, FALSE, NULL) ? FALSE : TRUE; */ mstr_native_align = FALSE; /* TODO: remove this line and uncomment the above line */ getjobname(); INVOKE_INIT_SECSHR_ADDRS; getzprocess(); getzmode(); geteditor(); zcall_init(); cmd_qlf.qlf = glb_cmd_qlf.qlf; cache_init(); # ifdef __sun if (NULL != GETENV(PACKAGE_ENV_TYPE)) /* chose xcall (default) or rpc zcall */ xfer_table[xf_fnfgncal] = (xfer_entry_t)op_fnfgncal_rpc; /* using RPC */ # endif msp -= SIZEOF(stack_frame); frame_pointer = (stack_frame *)msp; memset(frame_pointer,0, SIZEOF(stack_frame)); frame_pointer->temps_ptr = (unsigned char *)frame_pointer; frame_pointer->ctxt = GTM_CONTEXT(gtm_ret_code); frame_pointer->mpc = CODE_ADDRESS(gtm_ret_code); frame_pointer->type = SFT_COUNT; frame_pointer->rvector = (rhdtyp*)malloc(SIZEOF(rhdtyp)); memset(frame_pointer->rvector, 0, SIZEOF(rhdtyp)); symbinit(); /* Variables for supporting $ZSEARCH sorting and wildcard expansion */ TREF(zsearch_var) = lv_getslot(curr_symval); TREF(zsearch_dir1) = lv_getslot(curr_symval); TREF(zsearch_dir2) = lv_getslot(curr_symval); LVVAL_INIT((TREF(zsearch_var)), curr_symval); LVVAL_INIT((TREF(zsearch_dir1)), curr_symval); LVVAL_INIT((TREF(zsearch_dir2)), curr_symval); /* Initialize global pointer to control-C handler. Also used in iott_use */ ctrlc_handler_ptr = &ctrlc_handler; io_init(IS_MUPIP_IMAGE); /* starts with nocenable for GT.M runtime, enabled for MUPIP */ if (!IS_MUPIP_IMAGE) { sig_init(generic_signal_handler, ctrlc_handler_ptr, suspsigs_handler, continue_handler); atexit(gtm_exit_handler); cenable(); /* cenable unless the environment indicates otherwise - 2 steps because this can report errors */ } jobinterrupt_init(); getzdir(); dpzgbini(); zco_init(); /* a base addr of 0 indicates a gtm_init call from an rpc server */ if ((GTM_IMAGE == image_type) && (NULL != svec->base_addr)) jobchild_init(); else { /* Trigger enabled utilities will enable through here */ (TREF(dollar_zmode)).mvtype = MV_STR; (TREF(dollar_zmode)).str.addr = other_mode_buf; (TREF(dollar_zmode)).str.len = SIZEOF(other_mode_buf) -1; } svec->frm_ptr = (unsigned char *)frame_pointer; dollar_ztrap.mvtype = MV_STR; dollar_ztrap.str.len = SIZEOF(init_break); dollar_ztrap.str.addr = (char *)init_break; dollar_zstatus.mvtype = MV_STR; dollar_zstatus.str.len = 0; dollar_zstatus.str.addr = NULL; ecode_init(); zyerror_init(); ztrap_form_init(); ztrap_new_init(); zdate_form_init(svec); dollar_system_init(svec); init_callin_functable(); gtm_env_xlate_init(); SET_LATCH_GLOBAL(&defer_latch, LOCK_AVAILABLE); curr_pattern = pattern_list = &mumps_pattern; pattern_typemask = mumps_pattern.typemask; initialize_pattern_table(); ce_init(); /* initialize compiler escape processing */ /* Initialize local collating sequence */ TREF(transform) = TRUE; lct = find_local_colltype(); if (lct != 0) { TREF(local_collseq) = ready_collseq(lct); if (!TREF(local_collseq)) { exi_condition = -ERR_COLLATIONUNDEF; gtm_putmsg(VARLSTCNT(3) ERR_COLLATIONUNDEF, 1, lct); exit(exi_condition); } } else TREF(local_collseq) = 0; prealloc_gt_timers(); gt_timers_add_safe_hndlrs(); for (i = 0; FNPC_MAX > i; i++) { /* Initialize cache structure for $Piece function */ (TREF(fnpca)).fnpcs[i].pcoffmax = &(TREF(fnpca)).fnpcs[i].pstart[FNPC_ELEM_MAX]; (TREF(fnpca)).fnpcs[i].indx = i; } (TREF(fnpca)).fnpcsteal = (TREF(fnpca)).fnpcs; /* Starting place to look for cache reuse */ (TREF(fnpca)).fnpcmax = &(TREF(fnpca)).fnpcs[FNPC_MAX - 1]; /* The last element */ /* Initialize zwrite subsystem. Better to do it now when we have storage to allocate than * if we fail and storage allocation may not be possible. To that end, pretend we have * seen alias acitivity so those structures are initialized as well. */ assert(FALSE == curr_symval->alias_activity); curr_symval->alias_activity = TRUE; lvzwr_init((enum zwr_init_types)0, (mval *)NULL); curr_symval->alias_activity = FALSE; if ((NULL != (TREF(mprof_env_gbl_name)).str.addr)) turn_tracing_on(TADR(mprof_env_gbl_name), TRUE, (TREF(mprof_env_gbl_name)).str.len > 0); return; }
int main(int argc, char** argv) { int wstat, ret; pid_t pid; struct timeval tv; service_t *svc; // initialize wake structure, which is owned by main memset(wake, 0, sizeof(*wake)); // just in case, but probably redundant FD_ZERO(&wake->fd_read); FD_ZERO(&wake->fd_write); FD_ZERO(&wake->fd_err); FD_ZERO(&wake->fd_ready_read); FD_ZERO(&wake->fd_ready_write); FD_ZERO(&wake->fd_ready_err); // wake structure holds current time so we don't keep calling clock_gettime() wake->now= gettime_mon_frac(); log_init(); svc_init(); fd_init(); ctl_init(); // Special defaults when running as init if (getpid() == 1) { opt_config_file= CONFIG_FILE_DEFAULT_PATH; opt_terminate_guard= 1; } umask(077); // parse arguments, overriding default values parse_opts(argv+1); // Check for required options if (!opt_interactive && !opt_config_file && !opt_socket_path) fatal(EXIT_BAD_OPTIONS, "require -i or -c or -S"); // Initialize file descriptor object pool if (opt_fd_pool_count > 0 && opt_fd_pool_size_each > 0) if (!fd_preallocate(opt_fd_pool_count, opt_fd_pool_size_each)) fatal(EXIT_INVALID_ENVIRONMENT, "Unable to preallocate file descriptor objects"); if (!fd_init_special_handles()) fatal(EXIT_BROKEN_PROGRAM_STATE, "Can't initialize all special handles"); if (!register_open_fds()) fatal(EXIT_BAD_OPTIONS, "Not enough FD objects to register all open FDs"); // Set up signal handlers and signal mask and signal self-pipe // Do this AFTER registering all open FDs, because it creates a pipe sig_init(); // Initialize service object pool if (opt_svc_pool_count > 0 && opt_svc_pool_size_each > 0) if (!svc_preallocate(opt_svc_pool_count, opt_svc_pool_size_each)) fatal(EXIT_INVALID_ENVIRONMENT, "Unable to preallocate service objects"); // Initialize controller object pool control_socket_init(); if (opt_socket_path && !control_socket_start(STRSEG(opt_socket_path))) fatal(EXIT_INVALID_ENVIRONMENT, "Can't create controller socket"); if (opt_interactive) if (!setup_interactive_mode()) fatal(EXIT_INVALID_ENVIRONMENT, "stdin/stdout are not usable!"); if (opt_config_file) if (!setup_config_file(opt_config_file)) fatal(EXIT_INVALID_ENVIRONMENT, "Unable to process config file"); if (opt_mlockall) { // Lock all memory into ram. init should never be "swapped out". if (mlockall(MCL_CURRENT | MCL_FUTURE)) log_error("mlockall: %s", strerror(errno)); } // fork and setsid if requested, but not if PID 1 or interactive if (opt_daemonize) { if (getpid() == 1 || opt_interactive) log_warn("Ignoring --daemonize (see manual)"); else daemonize(); } // terminate is disabled when running as init, so this is an infinite loop // (except when debugging) wake->now= gettime_mon_frac(); while (!main_terminate) { // set our wait parameters so other methods can inject new wake reasons wake->next= wake->now + (200LL<<32); // wake at least every 200 seconds wake->max_fd= -1; log_run(); // collect new signals since last iteration and set read-wake on signal fd sig_run(); // reap all zombies, possibly waking services while ((pid= waitpid(-1, &wstat, WNOHANG)) > 0) { log_trace("waitpid found pid = %d", (int)pid); if ((svc= svc_by_pid(pid))) svc_handle_reaped(svc, wstat); else log_trace("pid does not belong to any service"); } if (pid < 0) log_trace("waitpid: %s", strerror(errno)); // run state machine of each service that is active. svc_run_active(); // possibly accept new controller connections control_socket_run(); // run controller state machines ctl_run(); log_run(); // Wait until an event or the next time a state machine needs to run // (state machines edit wake.next) wake->now= gettime_mon_frac(); if (wake->next - wake->now > 0) { tv.tv_sec= (long)((wake->next - wake->now) >> 32); tv.tv_usec= (long)((((wake->next - wake->now)&0xFFFFFFFFLL) * 1000000) >> 32); log_trace("wait up to %d.%d sec", tv.tv_sec, tv.tv_usec); } else