int install_crash_handler(void (*handler)(int)) { return install_sighandler(SIGSEGV, handler, true) || install_sighandler(SIGABRT, handler, true) || install_sighandler(SIGBUS, handler, true) || install_sighandler(SIGILL, handler, true) || install_sighandler(SIGFPE, handler, true); }
/* * Many operating systems allow signals to be sent to running * processes. Some signals have a defined effect on the process, while * others may be trapped at the code level and acted upon. For * example, your process may trap the USR1 signal and use it to toggle * debugging, and may use TERM to initiate a controlled shutdown. * * pid = fork do * Signal.trap("USR1") do * $debug = !$debug * puts "Debug now: #$debug" * end * Signal.trap("TERM") do * puts "Terminating..." * shutdown() * end * # . . . do some work . . . * end * * Process.detach(pid) * * # Controlling program: * Process.kill("USR1", pid) * # ... * Process.kill("USR1", pid) * # ... * Process.kill("TERM", pid) * * produces: * Debug now: true * Debug now: false * Terminating... * * The list of available signal names and their interpretation is * system dependent. Signal delivery semantics may also vary between * systems; in particular signal delivery may not always be reliable. */ void Init_signal(void) { VALUE mSignal = rb_define_module("Signal"); rb_define_global_function("trap", sig_trap, -1); rb_define_module_function(mSignal, "trap", sig_trap, -1); rb_define_module_function(mSignal, "list", sig_list, 0); rb_define_method(rb_eSignal, "initialize", esignal_init, -1); rb_define_method(rb_eSignal, "signo", esignal_signo, 0); rb_alias(rb_eSignal, rb_intern("signm"), rb_intern("message")); rb_define_method(rb_eInterrupt, "initialize", interrupt_init, -1); install_sighandler(SIGINT, sighandler); #ifdef SIGHUP install_sighandler(SIGHUP, sighandler); #endif #ifdef SIGQUIT install_sighandler(SIGQUIT, sighandler); #endif #ifdef SIGTERM install_sighandler(SIGTERM, sighandler); #endif #ifdef SIGALRM install_sighandler(SIGALRM, sighandler); #endif #ifdef SIGUSR1 install_sighandler(SIGUSR1, sighandler); #endif #ifdef SIGUSR2 install_sighandler(SIGUSR2, sighandler); #endif #ifdef RUBY_DEBUG_ENV if (!ruby_enable_coredump) #endif { #ifdef SIGBUS install_sighandler(SIGBUS, sigbus); #endif #ifdef SIGSEGV # ifdef USE_SIGALTSTACK rb_register_sigaltstack(GET_THREAD()); # endif install_sighandler(SIGSEGV, (sighandler_t)sigsegv); #endif } #ifdef SIGPIPE install_sighandler(SIGPIPE, sigpipe); #endif #if defined(SIGCLD) init_sigchld(SIGCLD); #elif defined(SIGCHLD) init_sigchld(SIGCHLD); #endif }
/* * Many operating systems allow signals to be sent to running * processes. Some signals have a defined effect on the process, while * others may be trapped at the code level and acted upon. For * example, your process may trap the USR1 signal and use it to toggle * debugging, and may use TERM to initiate a controlled shutdown. * * pid = fork do * Signal.trap("USR1") do * $debug = !$debug * puts "Debug now: #$debug" * end * Signal.trap("TERM") do * puts "Terminating..." * shutdown() * end * # . . . do some work . . . * end * * Process.detach(pid) * * # Controlling program: * Process.kill("USR1", pid) * # ... * Process.kill("USR1", pid) * # ... * Process.kill("TERM", pid) * * produces: * Debug now: true * Debug now: false * Terminating... * * The list of available signal names and their interpretation is * system dependent. Signal delivery semantics may also vary between * systems; in particular signal delivery may not always be reliable. */ void Init_signal(void) { #ifndef MACOS_UNUSE_SIGNAL VALUE mSignal = rb_define_module("Signal"); rb_define_global_function("trap", sig_trap, -1); rb_define_module_function(mSignal, "trap", sig_trap, -1); rb_define_module_function(mSignal, "list", sig_list, 0); rb_define_method(rb_eSignal, "initialize", esignal_init, -1); rb_attr(rb_eSignal, rb_intern("signo"), 1, 0, 0); rb_alias(rb_eSignal, rb_intern("signm"), rb_intern("message")); rb_define_method(rb_eInterrupt, "initialize", interrupt_init, -1); install_sighandler(SIGINT, sighandler); #ifdef SIGHUP install_sighandler(SIGHUP, sighandler); #endif #ifdef SIGQUIT install_sighandler(SIGQUIT, sighandler); #endif #ifdef SIGTERM install_sighandler(SIGTERM, sighandler); #endif #ifdef SIGALRM install_sighandler(SIGALRM, sighandler); #endif #ifdef SIGUSR1 install_sighandler(SIGUSR1, sighandler); #endif #ifdef SIGUSR2 install_sighandler(SIGUSR2, sighandler); #endif #ifdef RUBY_DEBUG_ENV if (!ruby_enable_coredump) #endif { #ifdef SIGBUS install_sighandler(SIGBUS, sigbus); #endif #ifdef SIGSEGV install_sighandler(SIGSEGV, sigsegv); #endif } #ifdef SIGPIPE install_sighandler(SIGPIPE, sigpipe); #endif #if defined(SIGCLD) init_sigchld(SIGCLD); #elif defined(SIGCHLD) init_sigchld(SIGCHLD); #endif #endif /* MACOS_UNUSE_SIGNAL */ }
/* * Many operating systems allow signals to be sent to running * processes. Some signals have a defined effect on the process, while * others may be trapped at the code level and acted upon. For * example, your process may trap the USR1 signal and use it to toggle * debugging, and may use TERM to initiate a controlled shutdown. * * pid = fork do * Signal.trap("USR1") do * $debug = !$debug * puts "Debug now: #$debug" * end * Signal.trap("TERM") do * puts "Terminating..." * shutdown() * end * # . . . do some work . . . * end * * Process.detach(pid) * * # Controlling program: * Process.kill("USR1", pid) * # ... * Process.kill("USR1", pid) * # ... * Process.kill("TERM", pid) * * produces: * Debug now: true * Debug now: false * Terminating... * * The list of available signal names and their interpretation is * system dependent. Signal delivery semantics may also vary between * systems; in particular signal delivery may not always be reliable. */ void Init_signal(void) { #ifndef MACOS_UNUSE_SIGNAL VALUE mSignal = rb_define_module("Signal"); rb_define_global_function("trap", sig_trap, -1); rb_define_module_function(mSignal, "trap", sig_trap, -1); rb_define_module_function(mSignal, "list", sig_list, 0); install_sighandler(SIGINT, sighandler); #ifdef SIGHUP install_sighandler(SIGHUP, sighandler); #endif #ifdef SIGQUIT install_sighandler(SIGQUIT, sighandler); #endif #ifdef SIGTERM install_sighandler(SIGTERM, sighandler); #endif #ifdef SIGALRM install_sighandler(SIGALRM, sighandler); #endif #ifdef SIGUSR1 install_sighandler(SIGUSR1, sighandler); #endif #ifdef SIGUSR2 install_sighandler(SIGUSR2, sighandler); #endif #ifdef SIGBUS install_sighandler(SIGBUS, sigbus); #endif #ifdef SIGSEGV install_sighandler(SIGSEGV, sigsegv); #endif #ifdef SIGPIPE install_sighandler(SIGPIPE, sigpipe); #endif #if defined(SIGCLD) init_sigchld(SIGCLD); #elif defined(SIGCHLD) init_sigchld(SIGCHLD); #endif #endif /* MACOS_UNUSE_SIGNAL */ }
void start_scan_sambaserver(int use_sys_timer) { //- Remove all smb_srv_info_t *c; for (c = smb_srv_info_list; c; c = c->next) { Cdbg(DBE, "remove , ip=[%s]\n", c->ip->ptr); DLIST_REMOVE(smb_srv_info_list,c); free(c); c = smb_srv_info_list; } free(smb_srv_info_list); init_a_srvInfo(); g_useSystemTimer = use_sys_timer; g_bInitialize = 1; #ifdef _USEMYTIMER if(g_useSystemTimer==0){ Cdbg(DBE, "create timer\n"); timer_t arp_timer = create_timer(TT_SIGUSR2); install_sighandler(TT_SIGUSR2, on_arpping_timer_handler); set_timer(arp_timer, ARP_TIME_INTERVAL); } #endif }
int main(int argc, char* argv[]) { char* buffer; size_t length, body_pos; struct artist_album_state state = {0}; int i; setlocale(LC_ALL, ""); install_sighandler(); httpreq(&buffer, &length); body_pos = http_body_offset(buffer, length); LOG(LOG_OK, "New relases:"); parse_json(buffer + body_pos, length - body_pos, (void*)&state, artist_album_cb); for (i = 0; i < state.result_index; i++) { printf("%d. %s\n", i, state.result[i]); } spotify_main_loop(argv[1], argv[2], spotify_callback); free(buffer); for (i = 0; i < state.result_index; i++) { free(state.result[i]); } return 0; }
/* * Many operating systems allow signals to be sent to running * processes. Some signals have a defined effect on the process, while * others may be trapped at the code level and acted upon. For * example, your process may trap the USR1 signal and use it to toggle * debugging, and may use TERM to initiate a controlled shutdown. * * pid = fork do * Signal.trap("USR1") do * $debug = !$debug * puts "Debug now: #$debug" * end * Signal.trap("TERM") do * puts "Terminating..." * shutdown() * end * # . . . do some work . . . * end * * Process.detach(pid) * * # Controlling program: * Process.kill("USR1", pid) * # ... * Process.kill("USR1", pid) * # ... * Process.kill("TERM", pid) * * produces: * Debug now: true * Debug now: false * Terminating... * * The list of available signal names and their interpretation is * system dependent. Signal delivery semantics may also vary between * systems; in particular signal delivery may not always be reliable. */ void Init_signal(void) { #ifndef MACOS_UNUSE_SIGNAL VALUE mSignal = rb_define_module("Signal"); rb_objc_define_module_function(rb_mKernel, "trap", sig_trap, -1); rb_objc_define_method(*(VALUE *)mSignal, "trap", sig_trap, -1); rb_objc_define_method(*(VALUE *)mSignal, "list", sig_list, 0); rb_objc_define_method(rb_eSignal, "initialize", esignal_init, -1); rb_objc_define_method(rb_eSignal, "signo", esignal_signo, 0); rb_alias(rb_eSignal, rb_intern("signm"), rb_intern("message")); rb_objc_define_method(rb_eInterrupt, "initialize", interrupt_init, -1); /* install_sighandler(SIGINT, sighandler); */ /* install_sighandler(SIGHUP, sighandler); */ /* install_sighandler(SIGQUIT, sighandler); */ /* install_sighandler(SIGTERM, sighandler); */ /* install_sighandler(SIGALRM, sighandler); */ /* install_sighandler(SIGUSR1, sighandler); */ /* install_sighandler(SIGUSR2, sighandler); */ #ifdef RUBY_DEBUG_ENV if (!ruby_enable_coredump) #endif install_sighandler(SIGPIPE, sigpipe); init_sigchld(SIGCHLD); #endif /* !MACOS_UNUSE_SIGNAL */ }
void mrb_mruby_signal_gem_init(mrb_state* mrb) { struct RClass *signal = mrb_define_module(mrb, "Signal"); mrb_obj_iv_set(mrb, (struct RObject *)signal, mrb_intern_lit(mrb, "trap_list"), mrb_ary_new_capa(mrb, NSIG)); mrb_define_class_method(mrb, signal, "trap", signal_trap, MRB_ARGS_ANY()); mrb_define_class_method(mrb, signal, "list", signal_list, MRB_ARGS_NONE()); mrb_define_class_method(mrb, signal, "signame", signal_signame, MRB_ARGS_REQ(1)); mrb_define_method(mrb, mrb->kernel_module, "trap", signal_trap, MRB_ARGS_ANY()); install_sighandler(mrb, SIGINT, sighandler); #ifdef SIGHUP install_sighandler(mrb, SIGHUP, sighandler); #endif #ifdef SIGQUIT install_sighandler(mrb, SIGQUIT, sighandler); #endif #ifdef SIGTERM install_sighandler(mrb, SIGTERM, sighandler); #endif #ifdef SIGALRM install_sighandler(mrb, SIGALRM, sighandler); #endif #ifdef SIGUSR1 install_sighandler(mrb, SIGUSR1, sighandler); #endif #ifdef SIGUSR2 install_sighandler(mrb, SIGUSR2, sighandler); #endif }
/// Install signal handlers static void install_sigs(void) { #ifdef SIGXFSZ // Some systems may send signal if our swapfiles get too large, but we have // our own ways of dealing with that eventuality. Ignore the signal. signal(SIGXFSZ, SIG_IGN); #endif // Install exit handler. These may not be repeatable, i.e. if the same signal // comes in again, we will probably just be terminated. But that's not // unreasonable, come to think of it. signal(SIGTERM, sighand_exit); signal(SIGHUP, sighand_exit); #ifdef SIGPWR signal(SIGPWR, sighand_exit); #endif // These handlers must be repeatable. install_sighandler(SIGUSR1, sighand_status); install_sighandler(SIGUSR2, sighand_diet); }
int main(int argc, char *argv[]) { parse_args(argc, argv); #ifdef CAPS_SUPPORT set_user(); set_caps(); #endif create_thread(); create_jvm(); install_sighandler(); run(); return 0; }
int main(int argc, char ** argv) { if (argc != 4) { return usage(argv[0]); } install_sighandler(); g_playlist_name = argv[3]; spotify_main_loop_init(argv[1], argv[2], spotify_callback); spotify_main_loop(); return EXIT_SUCCESS; }
int main(int argc, char **argv) { if (argc == 2) { port_name = argv[1]; } //printf("Using %s as serial device.\n", port_name); char ttybuf[255]; tty_fd = open_tty(); if (tty_fd < 0) { //printf("Error opening terminal.\n"); return (1); } install_sighandler(); if (init() < 0) { //printf("Cannot open port.\r\n"); exit(1); } while (1) { int n = read(tty_fd, ttybuf, sizeof(ttybuf)); int i; /* check for 0x3 (ctrl-c), clean exit */ for (i = 0; i < n; i++) { if (ttybuf[i] == 0x3) { if (i > 0) { write_serial_port(ttybuf, i); } close_serial_port(); close_tty(); system("tset -c"); return 0; } } write_serial_port(ttybuf, n); } close_tty(); close_serial_port(); return 0; }
int ttyHandler::openConnection() { install_sighandler(); m_mtxSerialPort.lock(); int result = m_sh.open_serial_port(m_strPort.c_str()); m_mtxSerialPort.unlock(); if(result < 0) return result; std::thread m_pReadThread(&ttyHandler::readPort, this, this ); m_pReadThread.detach(); hardResetToUserCode(); return result; }
/** * @brief 初始化 * * @return 成功返回0,失败返回失败的步骤 */ int init(int argc, char **argv) { init_print_level(); ///< console 消息级别 global_container_init(); ///<对象容器初始化 install_sighandler(); ///<安装信号处理函数 register_class(); poller_create(POLLER_MAX); app_init(argc, argv); if(system_threads() < 0) return -2; return 0; }
void start_scan_sambaserver(int use_sys_timer) { Cdbg(DBE, "start start_scan_sambaserver..."); //- Remove all smb_srv_info_t *c; for (c = smb_srv_info_list; c; c = c->next) { Cdbg(DBE, "remove , ip=[%s]\n", c->ip->ptr); DLIST_REMOVE(smb_srv_info_list,c); free(c); c = smb_srv_info_list; } free(smb_srv_info_list); read_arpping_list(); if( init_a_srvInfo() == 0 ) return; g_useSystemTimer = use_sys_timer; g_bInitialize = 1; #ifdef _USEMYTIMER if(g_useSystemTimer==0){ g_arp_timer = create_timer(TT_SIGUSR2); install_sighandler(TT_SIGUSR2, on_arpping_timer_handler2); set_timer(g_arp_timer, ARP_TIME_INTERVAL); } #endif #ifdef _USEMYTIMER2 struct itimerval tout_val; tout_val.it_interval.tv_sec = ARP_TIME_INTERVAL; tout_val.it_interval.tv_usec = 0; tout_val.it_value.tv_sec = ARP_TIME_INTERVAL; /* set timer for "INTERVAL (10) seconds */ tout_val.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &tout_val,0); signal(SIGALRM,on_arpping_timer_handler2); /* set the Alarm signal capture */ #endif }
int main(int argc, char **argv) { int ch, longindex, ret, port = SD_LISTEN_PORT, io_port = SD_LISTEN_PORT; int rc = 1; const char *dirp = DEFAULT_OBJECT_DIR, *short_options; char *dir, *p, *pid_file = NULL, *bindaddr = NULL, log_path[PATH_MAX], *argp = NULL; bool explicit_addr = false; bool daemonize = true; int32_t nr_vnodes = -1; int64_t zone = -1; struct cluster_driver *cdrv; struct option *long_options; const char *http_options = NULL; static struct logger_user_info sheep_info; struct stat logdir_st; enum log_dst_type log_dst_type; sys->cinfo.flags |= SD_CLUSTER_FLAG_AUTO_VNODES; sys->node_status = SD_NODE_STATUS_INITIALIZATION; sys->rthrottling.max_exec_count = 0; sys->rthrottling.queue_work_interval = 0; sys->rthrottling.throttling = false; install_crash_handler(crash_handler); signal(SIGPIPE, SIG_IGN); install_sighandler(SIGHUP, sighup_handler, false); long_options = build_long_options(sheep_options); short_options = build_short_options(sheep_options); while ((ch = getopt_long(argc, argv, short_options, long_options, &longindex)) >= 0) { switch (ch) { case 'p': port = strtol(optarg, &p, 10); if (optarg == p || port < 1 || UINT16_MAX < port || *p != '\0') { sd_err("Invalid port number '%s'", optarg); exit(1); } break; case 'P': pid_file = optarg; break; case 'r': http_options = optarg; break; case 'l': if (option_parse(optarg, ",", log_parsers) < 0) exit(1); break; case 'n': sys->nosync = true; break; case 'y': if (!str_to_addr(optarg, sys->this_node.nid.addr)) { sd_err("Invalid address: '%s'", optarg); exit(1); } explicit_addr = true; break; case 'D': sys->backend_dio = true; break; case 'f': daemonize = false; break; case 'g': if (nr_vnodes > 0) { sd_err("Options '-g' and '-V' can not be both specified"); exit(1); } nr_vnodes = 0; break; case 'z': zone = strtol(optarg, &p, 10); if (optarg == p || zone < 0 || UINT32_MAX < zone || *p != '\0') { sd_err("Invalid zone id '%s': must be " "an integer between 0 and %u", optarg, UINT32_MAX); exit(1); } sys->this_node.zone = zone; break; case 'u': sys->upgrade = true; break; case 'c': sys->cdrv = find_cdrv(optarg); if (!sys->cdrv) { sd_err("Invalid cluster driver '%s'", optarg); fprintf(stderr, "Supported drivers:"); FOR_EACH_CLUSTER_DRIVER(cdrv) { fprintf(stderr, " %s", cdrv->name); } fprintf(stderr, "\n"); exit(1); } sys->cdrv_option = get_cdrv_option(sys->cdrv, optarg); break; case 'w': sys->enable_object_cache = true; sys->object_cache_size = 0; if (option_parse(optarg, ",", cache_parsers) < 0) exit(1); if (sys->object_cache_size == 0) { sd_err("object cache size is not set"); exit(1); } break; case 'i': if (option_parse(optarg, ",", ionic_parsers) < 0) exit(1); if (!str_to_addr(io_addr, sys->this_node.nid.io_addr)) { sd_err("Bad addr: '%s'", io_addr); exit(1); } if (io_pt) if (sscanf(io_pt, "%u", &io_port) != 1) { sd_err("Bad port '%s'", io_pt); exit(1); } sys->this_node.nid.io_port = io_port; break; case 'j': uatomic_set_true(&sys->use_journal); if (option_parse(optarg, ",", journal_parsers) < 0) exit(1); if (!jsize) { sd_err("you must specify size for journal"); exit(1); } break; case 'b': if (!inetaddr_is_valid(optarg)) exit(1); bindaddr = optarg; break; case 'h': usage(0); break; case 'R': if (option_parse(optarg, ",", recovery_parsers) < 0) exit(1); sys->rthrottling.max_exec_count = max_exec_count; sys->rthrottling.queue_work_interval = queue_work_interval; if (max_exec_count > 0 && queue_work_interval > 0) sys->rthrottling.throttling = true; break; case 'v': fprintf(stdout, "Sheepdog daemon version %s\n", PACKAGE_VERSION); exit(0); break; case 'V': sys->cinfo.flags &= ~SD_CLUSTER_FLAG_AUTO_VNODES; if (nr_vnodes == 0) { sd_err("Options '-g' and '-V' can not be both specified"); exit(1); } nr_vnodes = strtol(optarg, &p, 10); if (optarg == p || nr_vnodes < 1 || UINT16_MAX < nr_vnodes || *p != '\0') { sd_err("Invalid number of vnodes '%s': must be " "an integer between 1 and %u", optarg, UINT16_MAX); exit(1); } break; case 'W': wildcard_recovery = true; break; default: usage(1); break; } }
void logger::init(const config_tree& a_cfg, const sigset_t* a_ignore_signals, bool a_install_finalizer) { if (m_initialized) throw std::runtime_error("Logger already initialized!"); std::lock_guard<std::mutex> guard(m_mutex); do_finalize(); try { m_show_location = a_cfg.get<bool> ("logger.show-location", m_show_location); m_show_fun_namespaces = a_cfg.get<int> ("logger.show-fun-namespaces", m_show_fun_namespaces); m_show_category = a_cfg.get<bool> ("logger.show-category", m_show_category); m_show_ident = a_cfg.get<bool> ("logger.show-ident", m_show_ident); m_show_thread = a_cfg.get<bool> ("logger.show-thread", m_show_thread); m_fatal_kill_signal = a_cfg.get<int> ("logger.fatal-kill-signal",m_fatal_kill_signal); m_ident = a_cfg.get<std::string>("logger.ident", m_ident); m_ident = replace_macros(m_ident); std::string ts = a_cfg.get<std::string>("logger.timestamp", "time-usec"); m_timestamp_type = parse_stamp_type(ts); std::string levs = a_cfg.get<std::string>("logger.levels", ""); if (!levs.empty()) set_level_filter(static_cast<log_level>(parse_log_levels(levs))); std::string ls = a_cfg.get<std::string>("logger.min-level-filter", "info"); if (!levs.empty() && !ls.empty()) std::runtime_error ("Either 'levels' or 'min-level-filter' option is permitted!"); set_min_level_filter(parse_log_level(ls)); long timeout_ms = a_cfg.get<int> ("logger.wait-timeout-ms", 1000); m_wait_timeout = timespec{timeout_ms / 1000, timeout_ms % 1000 * 1000000L}; m_sched_yield_us = a_cfg.get<long> ("logger.sched-yield-us", -1); m_silent_finish = a_cfg.get<bool> ("logger.silent-finish", false); m_block_signals = a_cfg.get<bool> ("logger.block-signals", true); if ((int)m_timestamp_type < 0) throw std::runtime_error("Invalid timestamp type: " + ts); // Install crash signal handlers // (SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGTERM) if (a_cfg.get("logger.handle-crash-signals", true)) { sigset_t sset = sig_members_parse (a_cfg.get("logger.handle-crash-signals.signals",""), UTXX_SRC); // Remove signals from the sset that are handled externally if (a_ignore_signals) for (uint i=1; i < sig_names_count(); ++i) if (sigismember(a_ignore_signals, i)) sigdelset(&sset, i); if (install_sighandler(true, &sset)) { auto old = m_crash_sigset.exchange(new sigset_t(sset)); if (!old) delete old; } } //logger_impl::msg_info info(NULL, 0); //query_timestamp(info); logger_impl_mgr& lim = logger_impl_mgr::instance(); std::lock_guard<std::mutex> guard(lim.mutex()); // Check the list of registered implementations. If corresponding // configuration section is found, initialize the implementation. for(logger_impl_mgr::impl_map_t::iterator it=lim.implementations().begin(); it != lim.implementations().end(); ++it) { std::string path = std::string("logger.") + it->first; if (a_cfg.get_child_optional(path)) { // Determine if implementation of this type is already // registered with the logger bool found = false; for(implementations_vector::iterator im = m_implementations.begin(), iend = m_implementations.end(); im != iend; ++im) if (it->first == (*im)->name()) { found = true; break; } if (found) throw badarg_error("Implementation '", it->first, "' is already registered with the logger!"); // A call to it->second() creates a logger_impl* pointer. // We need to call implementation's init function that may throw, // so use RAII to guarantee proper cleanup. logger_impl_mgr::impl_callback_t& f = it->second; m_implementations.emplace_back( f(it->first.c_str()) ); auto& i = m_implementations.back(); i->set_log_mgr(this); i->init(a_cfg); } } m_initialized = true; m_abort = false; m_thread.reset(new std::thread([this]() { this->run(); })); if (!m_finalizer_installed && a_install_finalizer) { atexit(&finalize_logger_at_exit); m_finalizer_installed = true; } } catch (std::runtime_error& e) { if (m_error) m_error(e.what()); else throw; } }
/* the main program... */ int main(int argc, char *argv[]) { int i; sigset_t signalmask, oldmask; #ifdef HAVE_PTHREAD_TIMEDJOIN_NP struct timespec ts; #endif /* HAVE_PTHREAD_TIMEDJOIN_NP */ /* close all file descriptors (except stdin/out/err) */ i = sysconf(_SC_OPEN_MAX) - 1; /* if the system does not have OPEN_MAX just close the first 32 and hope we closed enough */ if (i < 0) i = 32; for (; i > 3; i--) close(i); /* parse the command line */ parse_cmdline(argc, argv); /* clean the environment */ #ifdef HAVE_CLEARENV if (clearenv() || putenv("HOME=/") || putenv("TMPDIR=/tmp") || putenv("LDAPNOINIT=1")) { log_log(LOG_ERR, "clearing environment failed"); exit(EXIT_FAILURE); } #else /* not HAVE_CLEARENV */ /* this is a bit ugly */ environ = sane_environment; #endif /* not HAVE_CLEARENV */ /* disable the nss_ldap module for this process */ disable_nss_ldap(); /* set LDAP log level */ if (myldap_set_debuglevel(nslcd_debugging) != LDAP_SUCCESS) exit(EXIT_FAILURE); /* read configuration file */ cfg_init(NSLCD_CONF_PATH); /* set default mode for pidfile and socket */ (void)umask((mode_t)0022); /* see if someone already locked the pidfile if --check option was given exit TRUE if daemon runs (pidfile locked), FALSE otherwise */ if (nslcd_checkonly) { if (is_locked(NSLCD_PIDFILE)) { log_log(LOG_DEBUG, "pidfile (%s) is locked", NSLCD_PIDFILE); exit(EXIT_SUCCESS); } else { log_log(LOG_DEBUG, "pidfile (%s) is not locked", NSLCD_PIDFILE); exit(EXIT_FAILURE); } } /* normal check for pidfile locked */ if (is_locked(NSLCD_PIDFILE)) { log_log(LOG_ERR, "daemon may already be active, cannot acquire lock (%s): %s", NSLCD_PIDFILE, strerror(errno)); exit(EXIT_FAILURE); } /* daemonize */ if ((!nslcd_debugging) && (!nslcd_nofork) && (daemon(0, 0) < 0)) { log_log(LOG_ERR, "unable to daemonize: %s", strerror(errno)); exit(EXIT_FAILURE); } /* intilialize logging */ if (!nslcd_debugging) log_startlogging(); log_log(LOG_INFO, "version %s starting", VERSION); /* start subprocess to do invalidating if reconnect_invalidate is set */ for (i = 0; i < LM_NONE; i++) if (nslcd_cfg->reconnect_invalidate[i]) break; if (i < LM_NONE) invalidator_start(); /* write pidfile */ create_pidfile(NSLCD_PIDFILE); /* install handler to close stuff off on exit and log notice */ if (atexit(exithandler)) { log_log(LOG_ERR, "atexit() failed: %s", strerror(errno)); exit(EXIT_FAILURE); } /* create socket */ nslcd_serversocket = create_socket(NSLCD_SOCKET); if ((nslcd_cfg->gid != NOGID) && (nslcd_cfg->uidname != NULL)) { #ifdef HAVE_INITGROUPS /* load supplementary groups */ if (initgroups(nslcd_cfg->uidname, nslcd_cfg->gid) < 0) log_log(LOG_WARNING, "cannot initgroups(\"%s\",%d) (ignored): %s", nslcd_cfg->uidname, (int)nslcd_cfg->gid, strerror(errno)); else log_log(LOG_DEBUG, "initgroups(\"%s\",%d) done", nslcd_cfg->uidname, (int)nslcd_cfg->gid); #else /* not HAVE_INITGROUPS */ #ifdef HAVE_SETGROUPS /* just drop all supplemental groups */ if (setgroups(0, NULL) < 0) log_log(LOG_WARNING, "cannot setgroups(0,NULL) (ignored): %s", strerror(errno)); else log_log(LOG_DEBUG, "setgroups(0,NULL) done"); #else /* not HAVE_SETGROUPS */ log_log(LOG_DEBUG, "neither initgroups() or setgroups() available"); #endif /* not HAVE_SETGROUPS */ #endif /* not HAVE_INITGROUPS */ } /* change to nslcd gid */ if (nslcd_cfg->gid != NOGID) { if (setgid(nslcd_cfg->gid) != 0) { log_log(LOG_ERR, "cannot setgid(%d): %s", (int)nslcd_cfg->gid, strerror(errno)); exit(EXIT_FAILURE); } log_log(LOG_DEBUG, "setgid(%d) done", (int)nslcd_cfg->gid); } /* change to nslcd uid */ if (nslcd_cfg->uid != NOUID) { if (setuid(nslcd_cfg->uid) != 0) { log_log(LOG_ERR, "cannot setuid(%d): %s", (int)nslcd_cfg->uid, strerror(errno)); exit(EXIT_FAILURE); } log_log(LOG_DEBUG, "setuid(%d) done", (int)nslcd_cfg->uid); } /* block all these signals so our worker threads won't handle them */ sigemptyset(&signalmask); sigaddset(&signalmask, SIGHUP); sigaddset(&signalmask, SIGINT); sigaddset(&signalmask, SIGQUIT); sigaddset(&signalmask, SIGABRT); sigaddset(&signalmask, SIGPIPE); sigaddset(&signalmask, SIGTERM); sigaddset(&signalmask, SIGUSR1); sigaddset(&signalmask, SIGUSR2); pthread_sigmask(SIG_BLOCK, &signalmask, &oldmask); /* start worker threads */ log_log(LOG_INFO, "accepting connections"); nslcd_threads = (pthread_t *)malloc(nslcd_cfg->threads * sizeof(pthread_t)); if (nslcd_threads == NULL) { log_log(LOG_CRIT, "main(): malloc() failed to allocate memory"); exit(EXIT_FAILURE); } for (i = 0; i < nslcd_cfg->threads; i++) { if (pthread_create(&nslcd_threads[i], NULL, worker, NULL)) { log_log(LOG_ERR, "unable to start worker thread %d: %s", i, strerror(errno)); exit(EXIT_FAILURE); } } pthread_sigmask(SIG_SETMASK, &oldmask, NULL); /* install signalhandlers for some signals */ install_sighandler(SIGHUP, sig_handler); install_sighandler(SIGINT, sig_handler); install_sighandler(SIGQUIT, sig_handler); install_sighandler(SIGABRT, sig_handler); install_sighandler(SIGPIPE, SIG_IGN); install_sighandler(SIGTERM, sig_handler); install_sighandler(SIGUSR1, sig_handler); install_sighandler(SIGUSR2, SIG_IGN); /* wait until we received a signal */ while ((nslcd_receivedsignal == 0) || (nslcd_receivedsignal == SIGUSR1)) { sleep(INT_MAX); /* sleep as long as we can or until we receive a signal */ if (nslcd_receivedsignal == SIGUSR1) { log_log(LOG_INFO, "caught signal %s (%d), refresh retries", signame(nslcd_receivedsignal), nslcd_receivedsignal); myldap_immediate_reconnect(); nslcd_receivedsignal = 0; } } /* print something about received signal */ log_log(LOG_INFO, "caught signal %s (%d), shutting down", signame(nslcd_receivedsignal), nslcd_receivedsignal); /* cancel all running threads */ for (i = 0; i < nslcd_cfg->threads; i++) if (pthread_cancel(nslcd_threads[i])) log_log(LOG_WARNING, "failed to stop thread %d (ignored): %s", i, strerror(errno)); /* close server socket to trigger failures in threads waiting on accept() */ close(nslcd_serversocket); nslcd_serversocket = -1; /* if we can, wait a few seconds for the threads to finish */ #ifdef HAVE_PTHREAD_TIMEDJOIN_NP ts.tv_sec = time(NULL) + 3; ts.tv_nsec = 0; #endif /* HAVE_PTHREAD_TIMEDJOIN_NP */ for (i = 0; i < nslcd_cfg->threads; i++) { #ifdef HAVE_PTHREAD_TIMEDJOIN_NP pthread_timedjoin_np(nslcd_threads[i], NULL, &ts); #endif /* HAVE_PTHREAD_TIMEDJOIN_NP */ if (pthread_kill(nslcd_threads[i], 0) == 0) log_log(LOG_ERR, "thread %d is still running, shutting down anyway", i); } /* we're done */ return EXIT_FAILURE; }
int main(int argc, char **argv) { int ch, longindex, ret, port = SD_LISTEN_PORT, io_port = SD_LISTEN_PORT; int log_level = SDOG_INFO, nr_vnodes = SD_DEFAULT_VNODES; const char *dirp = DEFAULT_OBJECT_DIR, *short_options; char *dir, *p, *pid_file = NULL, *bindaddr = NULL, path[PATH_MAX], *argp = NULL, *logdir = NULL; bool is_daemon = true, to_stdout = false, explicit_addr = false; int64_t zone = -1; struct cluster_driver *cdrv; struct option *long_options; const char *log_format = "server", *http_address = NULL; static struct logger_user_info sheep_info; install_crash_handler(crash_handler); signal(SIGPIPE, SIG_IGN); install_sighandler(SIGHUP, sighup_handler, false); long_options = build_long_options(sheep_options); short_options = build_short_options(sheep_options); while ((ch = getopt_long(argc, argv, short_options, long_options, &longindex)) >= 0) { switch (ch) { case 'p': port = strtol(optarg, &p, 10); if (optarg == p || port < 1 || UINT16_MAX < port || *p != '\0') { sd_err("Invalid port number '%s'", optarg); exit(1); } break; case 'P': pid_file = optarg; break; case 'r': http_address = optarg; break; case 'f': is_daemon = false; break; case 'l': log_level = strtol(optarg, &p, 10); if (optarg == p || log_level < SDOG_EMERG || SDOG_DEBUG < log_level || *p != '\0') { sd_err("Invalid log level '%s'", optarg); sdlog_help(); exit(1); } break; case 'L': logdir = realpath(optarg, NULL); if (!logdir) { sd_err("%m"); exit(1); } break; case 'n': sys->nosync = true; break; case 'y': if (!str_to_addr(optarg, sys->this_node.nid.addr)) { sd_err("Invalid address: '%s'", optarg); exit(1); } explicit_addr = true; break; case 'd': /* removed soon. use loglevel instead */ log_level = SDOG_DEBUG; break; case 'D': sys->backend_dio = true; break; case 'g': /* same as '-v 0' */ //printf("wyh\n"); nr_vnodes = 0; //nr_vnodes = 5; break; case 'o': to_stdout = true; break; case 'z': zone = strtol(optarg, &p, 10); if (optarg == p || zone < 0 || UINT32_MAX < zone || *p != '\0') { sd_err("Invalid zone id '%s': must be " "an integer between 0 and %u", optarg, UINT32_MAX); exit(1); } sys->this_node.zone = zone; break; case 'u': sys->upgrade = true; break; case 'c': sys->cdrv = find_cdrv(optarg); if (!sys->cdrv) { sd_err("Invalid cluster driver '%s'", optarg); fprintf(stderr, "Supported drivers:"); FOR_EACH_CLUSTER_DRIVER(cdrv) { fprintf(stderr, " %s", cdrv->name); } fprintf(stderr, "\n"); exit(1); } sys->cdrv_option = get_cdrv_option(sys->cdrv, optarg); break; case 'w': object_cache_set(optarg); break; case 'i': parse_arg(optarg, ",", init_io_arg); if (!str_to_addr(io_addr, sys->this_node.nid.io_addr)) { sd_err("Bad addr: '%s'", io_addr); exit(1); } if (io_pt) if (sscanf(io_pt, "%u", &io_port) != 1) { sd_err("Bad port '%s'", io_pt); exit(1); } sys->this_node.nid.io_port = io_port; break; case 'j': uatomic_set_true(&sys->use_journal); parse_arg(optarg, ",", init_journal_arg); if (!jsize) { sd_err("you must specify size for journal"); exit(1); } break; case 'b': if (!inetaddr_is_valid(optarg)) exit(1); bindaddr = optarg; break; case 'h': usage(0); break; case 'v': fprintf(stdout, "Sheepdog daemon version %s\n", PACKAGE_VERSION); exit(0); break; case 'F': log_format = optarg; break; default: usage(1); break; } }
/* * Many operating systems allow signals to be sent to running * processes. Some signals have a defined effect on the process, while * others may be trapped at the code level and acted upon. For * example, your process may trap the USR1 signal and use it to toggle * debugging, and may use TERM to initiate a controlled shutdown. * * pid = fork do * Signal.trap("USR1") do * $debug = !$debug * puts "Debug now: #$debug" * end * Signal.trap("TERM") do * puts "Terminating..." * shutdown() * end * # . . . do some work . . . * end * * Process.detach(pid) * * # Controlling program: * Process.kill("USR1", pid) * # ... * Process.kill("USR1", pid) * # ... * Process.kill("TERM", pid) * * produces: * Debug now: true * Debug now: false * Terminating... * * The list of available signal names and their interpretation is * system dependent. Signal delivery semantics may also vary between * systems; in particular signal delivery may not always be reliable. */ void Init_signal(void) { VALUE mSignal = rb_define_module("Signal"); rb_define_global_function("trap", sig_trap, -1); rb_define_module_function(mSignal, "trap", sig_trap, -1); rb_define_module_function(mSignal, "list", sig_list, 0); rb_define_module_function(mSignal, "signame", sig_signame, 1); rb_define_method(rb_eSignal, "initialize", esignal_init, -1); rb_define_method(rb_eSignal, "signo", esignal_signo, 0); rb_alias(rb_eSignal, rb_intern_const("signm"), rb_intern_const("message")); rb_define_method(rb_eInterrupt, "initialize", interrupt_init, -1); /* At this time, there is no subthread. Then sigmask guarantee atomics. */ rb_disable_interrupt(); install_sighandler(SIGINT, sighandler); #ifdef SIGHUP install_sighandler(SIGHUP, sighandler); #endif #ifdef SIGQUIT install_sighandler(SIGQUIT, sighandler); #endif #ifdef SIGTERM install_sighandler(SIGTERM, sighandler); #endif #ifdef SIGALRM install_sighandler(SIGALRM, sighandler); #endif #ifdef SIGUSR1 install_sighandler(SIGUSR1, sighandler); #endif #ifdef SIGUSR2 install_sighandler(SIGUSR2, sighandler); #endif if (!ruby_enable_coredump) { #ifdef SIGBUS install_sighandler(SIGBUS, (sighandler_t)sigbus); #endif #ifdef SIGILL install_sighandler(SIGILL, (sighandler_t)sigill); #endif #ifdef SIGSEGV # ifdef USE_SIGALTSTACK rb_register_sigaltstack(GET_THREAD()); # endif install_sighandler(SIGSEGV, (sighandler_t)sigsegv); #endif } #ifdef SIGPIPE install_sighandler(SIGPIPE, SIG_IGN); #endif #if defined(SIGCLD) init_sigchld(SIGCLD); #elif defined(SIGCHLD) init_sigchld(SIGCHLD); #endif rb_enable_interrupt(); }
void xskin_start_interface( int pipe_in ) { int xskin_sc; XEvent xskin_e; XSetWindowAttributes xskin_attr; XSizeHints xskin_hint; XClassHint xskin_chint; XTextProperty ct; char *namlist[2]; /* setup window */ xskin_d = XOpenDisplay( NULL ); xskin_sc = DefaultScreen( xskin_d ); xskin_r = RootWindow( xskin_d, xskin_sc ); xskin_gc = DefaultGC( xskin_d, xskin_sc ); xskin_vis = DefaultVisual( xskin_d, xskin_sc ); xskin_depth = DefaultDepth( xskin_d, xskin_sc ); xskin_w = XCreateSimpleWindow( xskin_d, xskin_r, 0, 0, skin_width, skin_height, 0, WhitePixel( xskin_d, xskin_sc ), BlackPixel( xskin_d, xskin_sc ) ); xskin_attr.backing_store = True; xskin_attr.override_redirect = False; XChangeWindowAttributes( xskin_d, xskin_w, CWBackingStore|CWOverrideRedirect, &xskin_attr ); XSelectInput( xskin_d, xskin_w, KeyPressMask|ExposureMask| EnterWindowMask|LeaveWindowMask| ButtonPressMask|ButtonReleaseMask| Button1MotionMask ); xskin_hint.flags = USSize | PMinSize | PMaxSize | USPosition; xskin_hint.width = xskin_hint.min_width = xskin_hint.max_width = skin_width; xskin_hint.height = xskin_hint.min_height = xskin_hint.max_height = skin_height; XSetNormalHints( xskin_d, xskin_w, &xskin_hint ); xskin_chint.res_name = XSKIN_RES_NAME; xskin_chint.res_class = XSKIN_RES_CLASS; XSetClassHint( xskin_d, xskin_w, &xskin_chint ); namlist[0]=(char *)safe_malloc(strlen(XSKIN_WINDOW_NAME)+1); strcpy( namlist[0], XSKIN_WINDOW_NAME ); XmbTextListToTextProperty( xskin_d, namlist, 1, XCompoundTextStyle, &ct ); XSetWMName( xskin_d, xskin_w, &ct ); XSetWMIconName( xskin_d, xskin_w, &ct ); free(namlist[0]); /* setup pixmaps */ if ( load_skins()!=0 ) goto finish; XSetWindowBackgroundPixmap( xskin_d, xskin_w, xskin_back ); XClearWindow( xskin_d, xskin_w ); XMapWindow( xskin_d, xskin_w ); while( 1 ) { XNextEvent( xskin_d, &xskin_e ); if ( xskin_e.type == Expose ) break; } fshuf=0; frep=0; fequ=1; fpll=1; fplay=0; fpause=0; fremain=0; play_val=1; vol_val=50; last_current_time=0; total_time=0; speana_buf = NULL; strcpy( last_text, "welcome to timidity" ); install_sighandler(); repaint(); ts_spectrum( -1, speana_buf ); XFlush(xskin_d); xskin_jobs( pipe_in ); /* tskin main jobs */ finish: signal_vector(0); /* finish */ }
int main(int argc, char **argv) { isns_server_t *server; isns_source_t *source; isns_db_t *db; int c; #ifdef MTRACE mtrace(); #endif while ((c = getopt_long(argc, argv, "46c:d:Efhr:", options, NULL)) != -1) { switch (c) { case '4': opt_af = AF_INET; break; case '6': opt_af = AF_INET6; break; case 'c': opt_configfile = optarg; break; case 'd': isns_enable_debugging(optarg); break; case 'E': opt_esi = 0; break; case 'f': opt_foreground = 1; break; case 'h': usage(0, NULL); case 'r': if (!strcasecmp(optarg, "initiator")) opt_role = ROLE_INITIATOR; else if (!strcasecmp(optarg, "control") || !strcasecmp(optarg, "monitor")) opt_role = ROLE_MONITOR; else { isns_error("Unknown role \"%s\"\n", optarg); usage(1, NULL); } break; case 'V': printf("Open-iSNS version %s\n" "Copyright (C) 2007, Olaf Kirch <*****@*****.**>\n", OPENISNS_VERSION_STRING); return 0; default: usage(1, "Unknown option"); } } if (optind != argc) usage(1, NULL); /* If the config code derives the source name * automatically, we want it to be distinct from * any other source name (chosen by eg the iSCSI * initiator). Adding a suffix of ":isns" is a * somewhat lame attempt. */ isns_config.ic_source_suffix = "isns"; isns_read_config(opt_configfile); if (!isns_config.ic_source_name) usage(1, "Please specify an iSNS source name"); source = isns_source_create_iscsi(isns_config.ic_source_name); isns_write_pidfile(isns_config.ic_pidfile); if (!opt_foreground) { if (daemon(0, 0) < 0) isns_fatal("Unable to background server process\n"); isns_log_background(); isns_update_pidfile(isns_config.ic_pidfile); } install_sighandler(SIGTERM, sig_cleanup); install_sighandler(SIGINT, sig_cleanup); install_sighandler(SIGUSR2, sig_reread); /* Create a DB object that shadows our portal list. This is for ESI - * when an ESI comes in, the library will look up the portal in this * database, and update its mtime. By checking the mtime at regular * intervals, we can verify whether the server's ESIs actually * reach us. */ db = isns_db_open_shadow(&local_portals); server = isns_create_server(source, db, &isns_callback_service_ops); isns_server_set_scn_callback(server, scn_callback); run_discovery(server); return 0; }