void set_detach_on_hup(Window *dummy, char *unused, int value) { if(value) my_signal(SIGHUP, sig_detach, 0); else my_signal(SIGHUP, irc_exit_old, 0); }
int lscgid_main(int fd, char *argv0, const char *secret, char *pSock) { int ret; s_parent = getppid(); my_signal(SIGCHLD, sigchild); my_signal(SIGINT, sigterm); my_signal(SIGTERM, sigterm); my_signal(SIGHUP, sigusr1); my_signal(SIGUSR1, sigusr1); signal(SIGPIPE, SIG_IGN); s_uid = geteuid(); memcpy(s_pSecret, secret, 16); #ifdef HAS_CLOUD_LINUX #if defined(linux) || defined(__linux) || defined(__linux__) || defined(__gnu_linux__) if ((pSock = getenv("LVE_ENABLE")) != NULL) { s_enable_lve = atol(pSock); unsetenv("LVE_ENABLE"); pSock = NULL; } if (s_enable_lve && !s_uid) { load_lve_lib(); if (s_enable_lve) init_lve(); } #endif #endif #if defined(__FreeBSD__) //setproctitle( "%s", "httpd" ); #else memset(argv0, 0, strlen(argv0)); strcpy(argv0, "openlitespeed (lscgid)"); #endif ret = run(fd); if ((ret) && (pSock) && (strncasecmp(pSock, "uds:/", 5) == 0)) { pSock += 5; close(STDIN_FILENO); unlink(pSock); } return ret; }
static void start_sync(void) { my_signal(SIGUSR1, sig_func); my_signal(SIGUSR2, sig_func); sigemptyset(&mask_null); sigemptyset(&mask_neu); sigaddset(&mask_neu, SIGUSR1); sigaddset(&mask_neu, SIGUSR2); if (sigprocmask(SIG_BLOCK, &mask_neu, &mask_alt) < 0) { printf("Fehler bei sigprocmask() ...\n"); exit(EXIT_FAILURE); } }
void RepisaModelo::ObtenerConsulta() { QString ord; // if(GrupoBoton->button(1)->isChecked()) { ord="asc"; } // if(GrupoBoton->button(2)->isChecked()) { ord="desc"; } Ordenamiento=ord; OrderByCampo="codigo"; Modelo* ObjetoBusqueda=new Modelo(); switch (IndiceBusqueda) { case 0: ObjetoBusqueda->setCodigo(LineBuscar->text()); OrderByCampo="codigo"; break; case 1: ObjetoBusqueda->setCodigoImagen(LineBuscar->text()); OrderByCampo="codigo_imagen"; break; case 2: ObjetoBusqueda->setNombre(LineBuscar->text()); OrderByCampo="nombre"; break; default: break; } Bd->Fabrica->Conectar(); QString Extra=" order by "+OrderByCampo+" "+ord+" LIMIT "+QString::number(RegistrosBusqueda)+" offset 0"; QSqlQueryModel* Model= FabricaLocal->BuscarTabla(*ObjetoBusqueda,Extra,CAMPOS); Bd->Fabrica->Desconectar(); Model->setHeaderData(0,Qt::Horizontal,"Codigo"); Model->setHeaderData(1,Qt::Horizontal,"Nombre"); Model->setHeaderData(2,Qt::Horizontal,"Codigo Imagen"); Model->setHeaderData(3,Qt::Horizontal,"Ruta"); QList<bool> CamposVisibles; CamposVisibles.push_back(true); CamposVisibles.push_back(true); CamposVisibles.push_back(true); CamposVisibles.push_back(true); emit my_signal(Model,CamposVisibles); ActualizarMapa((ObjetoMaestro*)ObjetoBusqueda); }
void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen) { int n = 0; const int on = 1; char sendline[MAXLINE] = {0}; char recvline[MAXLINE + 1] = {0}; sigset_t sigset_alrm; socklen_t len ; struct sockaddr *preply_addr; preply_addr = my_malloc(servlen); //???为什么要这个? my_setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); my_signal(SIGALRM, recvfrom_alarm); my_sigemptyset(&sigset_alrm); my_sigaddset(&sigset_alrm, SIGALRM); while (my_fgets(sendline, MAXLINE, fp) != NULL) { my_sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen); alarm(5); while(1) { len = servlen; // DEBUG; // printf("recvfrom 前面!\n"); my_sigprocmask(SIG_UNBLOCK, &sigset_alrm, NULL); n = recvfrom(sockfd, recvline, MAXLINE, 0, preply_addr, &len); my_sigprocmask(SIG_BLOCK, &sigset_alrm, NULL); if (n < 0) { if (errno == EINTR) { break; } else { err_sys("recvfrom error"); } } else { recvline[n] = 0; sleep(1); printf("from %s: %s", my_sock_ntop_host(preply_addr, len), recvline); } }//while }//while free(preply_addr); }
/* nap_exit: cleans up and leaves */ void nap_exit (int really_quit, char *reason, char *format, ...) { if (dead == 1) { kill_all_threads(); exit(1); } else if (dead == 2) { kill_all_threads(); _exit(1); } else if (dead == 3) { kill_all_threads(); kill(getpid(), SIGKILL); } dead++; set_lastlog_size(NULL, NULL, 0); set_history_size(NULL, NULL, 0); if (really_quit) { kill_all_threads(); say("Signon time : %s", my_ctime(start_time)); say("Signoff time : %s", my_ctime(now)); say("Total uptime : %s", convert_time(now - start_time)); } do_hook(EXIT_LIST, "%s", reason ? reason : empty_string); if (reason) say("%s", reason); close_all_servers(); close_all_sockets(); if (term_initialized) { cursor_to_input(); term_cr(); term_clear_to_eol(); term_reset(); } remove_bindings(); clear_variables(); delete_all_windows(); destroy_call_stack(); write_unfinished_list(); debug_cleanup(); fprintf(stdout, "\r"); fflush(stdout); if (really_quit) exit(0); kill_all_threads(); my_signal(SIGABRT, SIG_DFL, 0); kill(getpid(), SIGABRT); kill(getpid(), SIGQUIT); exit(1); }
int main(void) { int i; for (i = SIGRTMIN; i <= SIGRTMAX; ++i) { breakpoint(); my_signal(i, handle_sigrt); my_raise(i); } atomic_printf("caught %d signals; expected %d\n", num_signals_caught, 1 + SIGRTMAX - SIGRTMIN); test_assert(1 + SIGRTMAX - SIGRTMIN == num_signals_caught); atomic_puts("EXIT-SUCCESS"); return 0; }
void set_up_signals() { my_signal(SIGILL, again_handler); #ifdef SIGTRAP my_signal(SIGTRAP, again_handler); #endif my_signal(SIGFPE, again_handler); #ifdef SIGBUS my_signal(SIGBUS, again_handler); #endif my_signal(SIGSEGV, again_handler); #ifdef SIGIOT my_signal(SIGIOT, again_handler); #endif #ifdef SIGEMT my_signal(SIGEMT, again_handler); #endif #ifdef SIGALRM my_signal(SIGALRM, again_handler); #endif my_signal(SIGINT, again_handler); }
static void dns_thread_signal_setup(void) { sigset_t set; /* Create SIGQUIT signal handler for this thread */ #if 0 signal(SIGQUIT, kill_dns_thread); #endif /* Use ircii's portable implementation of signal() instead */ my_signal(SIGQUIT, (sigfunc *) kill_dns_thread, 0); /* Fill set with every signal */ sigfillset(&set); /* Remove the SIGQUIT signal from the set */ sigdelset(&set, SIGQUIT); /* Apply the mask on this thread */ pthread_sigmask(SIG_BLOCK, &set, NULL); }
void initialise_signals (void) { DA_INIT (sig_info_table, struct sig_info); my_signal (SIGINT, termination_handler, 1); my_signal (SIGHUP, termination_handler, 1); my_signal (SIGTERM, termination_handler, 1); my_signal (SIGCONT, cont_handler, 0); my_signal (SIGTSTP, tstp_handler, 0); #ifdef SIGWINCH my_signal (SIGWINCH, winch_handler, 0); #endif sigfillset (&full_set); }
void badboy_fork () { int status, pid; status = fork (); badboy_pid = status; if (status == 0) /* badboy */ { #ifdef DEBUG_LATE_BADBOY sleep(ntries*MAX_TRY_TIME+10); #else badboy_loop (); #endif exit (0); /* tough guy */ } else if (status < 0) perror ("fork"); else /* parent watching over badboy */ { if (verbose_level > 3) printf ("badboy pid = %d\n", badboy_pid); /* don't trust the child to return at night */ my_signal (SIGALRM, monitor_fcn); alarm (ntries*MAX_TRY_TIME); pid = waitpid (-1, &status, WUNTRACED); if (pid <= 0) { perror ("wait"); } else { if (verbose_level > 3) printf ("pid %d exited with status %d\n", pid, status); #if 0 record_status(status); #endif } } /* parent */ alarm(0); }
void badboy_fork() { int status, pid; pid_t child; child = fork(); badboy_pid = status; switch (child) { case -1: perror("fork"); case 0: #ifdef DEBUG_LATE_BADBOY sleep(ntries * MAX_TRY_TIME + 10); #else badboy_loop(); #endif exit(0); default: if (verbose_level > 3) printf("badboy pid = %d\n", badboy_pid); /* don't trust the child to return at night */ my_signal(SIGALRM, monitor_fcn); alarm(ntries * MAX_TRY_TIME); pid = waitpid(-1, &status, WUNTRACED); if (pid <= 0) perror("wait"); else { if (verbose_level > 3) printf("pid %d exited with status %d\n", pid, status); #if 0 record_status(status); #endif } } alarm(0); }
/* ------------------------------------------------------------------- * main() * Entry point into Iperf * * sets up signal handlers * initialize global locks and conditions * parses settings from environment and command line * starts up server or client thread * waits for all threads to complete * ------------------------------------------------------------------- */ int main( int argc, char **argv ) { #ifdef WIN32 // Start winsock WSADATA wsaData; int rc; #endif // Set SIGTERM and SIGINT to call our user interrupt function my_signal( SIGTERM, Sig_Interupt ); my_signal( SIGINT, Sig_Interupt ); #ifndef WIN32 // SIGALRM=14, _NSIG=3... my_signal( SIGALRM, Sig_Interupt ); #endif #ifndef WIN32 // Ignore broken pipes signal(SIGPIPE,SIG_IGN); #endif #ifdef WIN32 // Start winsock rc = WSAStartup( 0x202, &wsaData ); WARN_errno( rc == SOCKET_ERROR, "WSAStartup" ); if (rc == SOCKET_ERROR) return 0; // Tell windows we want to handle our own signals SetConsoleCtrlHandler( sig_dispatcher, true ); #endif // Initialize global mutexes and conditions Condition_Initialize ( &ReportCond ); Condition_Initialize ( &ReportDoneCond ); Mutex_Initialize( &groupCond ); Mutex_Initialize( &clients_mutex ); // Initialize the thread subsystem thread_init( ); // Initialize the interrupt handling thread to 0 sThread = thread_zeroid(); // perform any cleanup when quitting Iperf atexit( cleanup ); // Allocate the "global" settings thread_Settings* ext_gSettings = new thread_Settings; // Initialize settings to defaults Settings_Initialize( ext_gSettings ); // read settings from environment variables Settings_ParseEnvironment( ext_gSettings ); // read settings from command-line parameters Settings_ParseCommandLine( argc, argv, ext_gSettings ); // Check for either having specified client or server if ( ext_gSettings->mThreadMode == kMode_Client || ext_gSettings->mThreadMode == kMode_Listener ) { #ifdef WIN32 // Start the server as a daemon // Daemon mode for non-windows in handled // in the listener_spawn function if ( isDaemon( ext_gSettings ) ) { CmdInstallService(argc, argv); return 0; } // Remove the Windows service if requested if ( isRemoveService( ext_gSettings ) ) { // remove the service if ( CmdRemoveService() ) { fprintf(stderr, "IPerf Service is removed.\n"); return 0; } } #endif // initialize client(s) if ( ext_gSettings->mThreadMode == kMode_Client ) { client_init( ext_gSettings ); } #ifdef HAVE_THREAD // start up the reporter and client(s) or listener { thread_Settings *into = NULL; // Create the settings structure for the reporter thread Settings_Copy( ext_gSettings, &into ); into->mThreadMode = kMode_Reporter; // Have the reporter launch the client or listener into->runNow = ext_gSettings; // Start all the threads that are ready to go thread_start( into ); } #else // No need to make a reporter thread because we don't have threads thread_start( ext_gSettings ); #endif } else { // neither server nor client mode was specified // print usage and exit #ifdef WIN32 // In Win32 we also attempt to start a previously defined service // Starting in 2.0 to restart a previously defined service // you must call iperf with "iperf -D" or using the environment variable SERVICE_TABLE_ENTRY dispatchTable[] = { { TEXT(SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main}, { NULL, NULL} }; // Only attempt to start the service if "-D" was specified if ( !isDaemon(ext_gSettings) || // starting the service by SCM, there is no arguments will be passed in. // the arguments will pass into Service_Main entry. !StartServiceCtrlDispatcher(dispatchTable) ) // If the service failed to start then print usage #endif fprintf( stderr, usage_short, argv[0], argv[0] ); return 0; } // wait for other (client, server) threads to complete thread_joinall(); // all done! return 0; } // end main
int main(int argc, char *argv[], char *envp[]) { char *channel; debug_init(); srand((unsigned)time(NULL)); time(&start_time); time(&idle_time); time(&now); #ifdef WINNT fprintf(stdout, "%s %s\r\n", nap_version, internal_version); fprintf(stdout, "%s\r\n", main_version); #else fprintf(stdout, "%s %s\n", nap_version, internal_version); fprintf(stdout, "%s\n", main_version); #endif channel = parse_args(argv, argc, envp); FD_ZERO(&readables); FD_ZERO(&writables); if (term_init(NULL)) _exit(1); /* my_signal(SIGQUIT, SIG_IGN, 0);*/ my_signal(SIGHUP, irc_exit_old, 0); my_signal(SIGTERM, irc_exit_old, 0); my_signal(SIGPIPE, SIG_IGN, 0); my_signal(SIGINT, cntl_c, 0); my_signal(SIGALRM, nothing, 0); my_signal(SIGCHLD, child_reap, 0); my_signal(SIGCONT, term_cont, 0); my_signal(SIGWINCH, sig_refresh_screen, 0); my_signal(SIGUSR1, sigusr1, 0); if (!init_screen()) { create_new_screen(); new_window(main_screen); } init_keys(); init_keys2(); init_variables(); #ifdef WANT_THREAD init_share_mutexes(); #ifdef WANT_NSLOOKUP start_dns(); #endif #ifdef WANT_MP3PLAYER start_mp3(); #endif #ifdef GTK start_tgtk(); #endif #endif build_status(current_window, NULL, 0); update_input(UPDATE_ALL); #ifndef WINNT charset_ibmpc(); #endif load_scripts(); read_unfinished_list(); if (auto_connect) { int serv = 0; reload_save(NULL, NULL, NULL, NULL, 0); if (starting_server != -1) serv = starting_server; connect_to_server_by_refnum(serv, -1, create); current_window->server = serv; xterm_settitle(); } else { if (do_get_napigator) get_napigator(); display_server_list(); } set_input_prompt(current_window, get_string_var(INPUT_PROMPT_VAR), 0); for (;;) io("main"); #ifdef GUI1 gui_exit(); #else nappanic("get_line() returned"); #endif return (-((int)0xdead)); }
int main (int argc, char **argv) { fd_set reads; int nread; unsigned short port; char *host; char *tmp; int t; char stuff[100]; #ifndef WINNT my_signal(SIGWINCH, SIG_IGN, 0); #endif my_signal(SIGHUP, SIG_IGN, 0); my_signal(SIGQUIT, SIG_IGN, 0); my_signal(SIGINT, ignore, 0); if (argc != 3) /* no socket is passed */ my_exit(1); host = argv[1]; port = (unsigned short)atoi(argv[2]); if (!port) my_exit(2); /* what the hey */ s = connect_by_number(host, &port, SERVICE_CLIENT, PROTOCOL_TCP, 0); if (s < 0) my_exit(23); /* * first line from a wserv program is the tty. this is so ircii * can grab the size of the tty, and have it changed. */ tmp = ttyname(0); snprintf(stuff, sizeof stuff, "%s\n", tmp); t = write(s, stuff, strlen(stuff)); term_init(NULL); printf("t is %d", t); /* * The select call.. reads from the socket, and from the window.. * and pipes the output from out to the other.. nice and simple */ for (;;) { FD_ZERO(&reads); FD_SET(0, &reads); FD_SET(s, &reads); if (select(s + 1, &reads, NULL, NULL, NULL) <= 0) if (errno == EINTR) continue; if (FD_ISSET(0, &reads)) { if ((nread = read(0, buffer, sizeof(buffer)))) write(s, buffer, nread); else my_exit(3); } if (FD_ISSET(s, &reads)) { if ((nread = read(s, buffer, sizeof(buffer)))) write(1, buffer, nread); else my_exit(4); } } my_exit(8); }
void reattach_tty(char *tty, char *password) { int s = -1; char *name; struct sockaddr_in addr; struct hostent *hp; int len = 0; fd_set rd_fd; struct timeval tm = {0}; char chr_c[] = "\003"; /* * this buffer has to be big enough to handle a full screen of * information from the detached process. */ unsigned char buffer[6 * BIG_BUFFER_SIZE + 1]; char *p; int port = 0; #if defined (TIOCGWINSZ) struct winsize window; #endif memset(&parm, 0, sizeof(struct param)); if (!(name = find_detach_socket(socket_path, tty))) { fprintf(stderr, "No detached process to attach to.\r\n"); _exit(1); } strcpy(parm.cookie, get_cookie(name)); if (!*parm.cookie) _exit(1); if ((p = strrchr(name, '/'))) p++; sscanf(p, "%d.%*s.%*s", &port); displays = 1; if ((s = socket(AF_INET, SOCK_STREAM, 0)) < 0) { displays = 0; _exit(1); } chmod(name, SOCKMODE); set_socket_options(s); memset(&addr, 0, sizeof(struct sockaddr_in)); addr.sin_port = htons(port); addr.sin_family = AF_INET; if ((hp = gethostbyname("localhost"))) memcpy(&addr.sin_addr, hp->h_addr, hp->h_length); else inet_aton("127.0.0.1", (struct in_addr *)&addr.sin_addr); if (connect(s, (struct sockaddr *)&addr, sizeof(addr)) < 0) { fprintf(stderr, "connection refused for %s\r\n", name); _exit(1); } parm.pid = getpid(); parm.pgrp = getpgrp(); parm.uid = getuid(); strcpy(parm.tty, ttyname(0)); strncpy(parm.termid, getenv("TERM"), 80); if (password) strncpy(parm.password, password, 60); fprintf(stderr, "attempting to wakeup %s\r\n", find_tty_name(name)); #if defined (TIOCGWINSZ) if (ioctl(0, TIOCGWINSZ, &window) > -1) { parm.cols = window.ws_col; parm.rows = window.ws_row; } else #endif { parm.cols = 79; parm.rows = 25; } write(s, &parm, sizeof(struct param)); sleep(2); alarm(15); len = read(s, &parm, sizeof(struct param)); alarm(0); if (len <= 0) { fprintf(stderr, "[1;37merror[0;37m reconnecting to %s\r\n", find_tty_name(name)); displays = 0; chmod(name, SOCKMODE); exit(1); } unlink(name); term_init(parm.termid); set_term_eight_bit(1); charset_ibmpc(); term_clear_screen(); term_resize(); term_move_cursor(0, 0); my_signal(SIGPIPE, handle_pipe, 0); my_signal(SIGINT, handle_ctrlc, 0); my_signal(SIGHUP, handle_hup, 0); /* * according to MHacker we need to set errno to 0 under BSD. * for some reason we get a address in use from a socket * */ errno = 0; while (1) { FD_ZERO(&rd_fd); FD_SET(0, &rd_fd); FD_SET(s, &rd_fd); tm.tv_sec = 2; switch (select(s + 1, &rd_fd, NULL, NULL, &tm)) { case -1: if (ctrl_c) { write(s, chr_c, 1); ctrl_c = 0; } else if (errno != EINTR) { close(s); _exit(1); } break; case 0: break; default: { if (FD_ISSET(0, &rd_fd)) { len = read(0, buffer, sizeof(buffer) - 1); write(s, buffer, len); } if (FD_ISSET(s, &rd_fd)) { len = read(s, buffer, sizeof(buffer) - 1); write(1, buffer, len); } } } } close(s); fprintf(stderr, "Never should have got here"); _exit(1); return; /* error return */ }
void dg_cli(FILE *fp, int sockfd, const SA *pservaddr, socklen_t servlen) { int n = 0; int maxfdp1 = 0; const int on = 1; char sendline[MAXLINE] = {0}; char recvline[MAXLINE] = {0}; fd_set rset; socklen_t len; struct sockaddr *preply_addr = NULL; preply_addr = my_malloc(servlen); my_setsockopt(sockfd, SOL_SOCKET, SO_BROADCAST, &on, sizeof(on)); my_pipe(pipefd); // printf("pipefd[0] = %d\n", pipefd[0]); //+ maxfdp1 = max(sockfd, pipefd[0]) + 1; FD_ZERO(&rset); my_signal(SIGALRM, recvfrom_alarm); while (my_fgets(sendline, MAXLINE, fp) != NULL ) { my_sendto(sockfd, sendline, strlen(sendline), 0, pservaddr, servlen); alarm(3); while (1) { FD_SET(sockfd, &rset); FD_SET(pipefd[0], &rset); if ( (n = select(maxfdp1, &rset, NULL, NULL, NULL)) < 0 ) { if (errno == EINTR) { DEBUG; printf("select errno = EINTR\n"); //+ continue; } else { err_sys("select error"); } } // printf("kankan!\n"); if ( FD_ISSET(sockfd, &rset) ) { len = servlen; n = my_recvfrom(sockfd, recvline, MAXLINE, 0, preply_addr, &len); recvline[n] = 0; printf("from %s: %s", my_sock_ntop(preply_addr, len), recvline); } if ( FD_ISSET(pipefd[0], &rset) ) { // printf("read 上面\n"); my_read(pipefd[0], &n, 1); //timer expired // printf("read 下面!\n"); break; } } } free(preply_addr); }
void PerfSocket::Send_TCP( void ) { if ( false ) { Client_Recv_TCP(); return; } // terminate loop nicely on user interupts sInterupted = false; SigfuncPtr oldINT = my_signal( SIGINT, Sig_Interupt ); SigfuncPtr oldPIPE = my_signal( SIGPIPE, Sig_Interupt ); int currLen; bool canRead; InitTransfer(); do { // If the input is from a // file, fill the buffer with // data from the file if ( mSettings->mFileInput ) { extractor->getNextDataBlock(mBuf); // If the first character is 'a' // change if to '0' so that the // server does not mistake it for // a Window Suggest option if ( mBuf[0] == 'a' ) mBuf[0] = '0'; canRead = extractor->canRead(); } else canRead = true; // perform write currLen = write( mSock, mBuf, mSettings->mBufLen ); mPacketTime.setnow(); if ( currLen < 0 ) { WARN_errno( currLen < 0, "write" ); break; } // periodically report bandwidths ReportPeriodicBW(); mTotalLen += currLen; } while ( ! (sInterupted || (mMode_time && mPacketTime.after( mEndTime )) || (!mMode_time && mTotalLen >= mAmount)) && canRead ); if ( oldINT != Sig_Interupt ) { // Return signal handlers to previous handlers my_signal( SIGINT, oldINT ); my_signal( SIGPIPE, oldPIPE ); } // shutdown sending connection and wait (read) // for the other side to shutdown shutdown( mSock, SHUT_WR ); currLen = read( mSock, mBuf, mSettings->mBufLen ); WARN_errno( currLen == SOCKET_ERROR, "read on server close" ); WARN( currLen > 0, "server sent unexpected data" ); // stop timing mEndTime.setnow(); sReporting.Lock(); ReportBW( mTotalLen, 0.0, mEndTime.subSec( mStartTime )); sReporting.Unlock(); if ( mSettings->mPrintMSS ) { // read the socket option for MSS (maximum segment size) ReportMSS( getsock_tcp_mss( mSock )); } }
int main (int argc, char **argv) { fd_set reads; int nread; char * port; char * host; char * tmp; char stuff[100]; my_signal(SIGHUP, SIG_IGN); my_signal(SIGQUIT, SIG_IGN); my_signal(SIGINT, ignore); my_signal(SIGWINCH, sigwinch_func); if (argc != 3) /* no socket is passed */ my_exit(1); host = argv[1]; port = argv[2]; if ((data = connectory(host, port)) < 0) my_exit(23); if ((cmd = connectory(host, port)) < 0) my_exit(25); /* * First thing we do is tell the parent what protocol we plan on * talking. We will start the protocol at version 4, for this is * the fourth generation of wservs. * * We cannot use 'snprintf' here because we do not have the compat * functions and some systems do not have snprintf! This use of * sprintf is demonstrably safe. */ sprintf(stuff, "version=%d\n", CURRENT_WSERV_VERSION); write(cmd, stuff, strlen(stuff)); /* * Next thing we take care of is to tell the parent client * what tty we are using and tell them what geometry our screen * is. This provides some amount of sanity against whatever * brain damage might occur. The parent client takes our word * for what size this screen should be, and handles it accordingly. * * Warning: I am using sprintf() and write() because previous * attempts to use writev() have shown that linux does not have * an atomic writev() function (boo, hiss). The parent client * does not take kindly to this data coming in multiple packets. */ tmp = ttyname(0); sprintf(stuff, "tty=%s\n", tmp); write(cmd, stuff, strlen(stuff)); term_init(); /* Set up the xterm */ term_resize(); /* Figure out how big xterm is and tell epic */ /* * The select call.. reads from the socket, and from the window.. * and pipes the output from out to the other.. nice and simple. * The command pipe is write-only. The parent client does not * send anything to us over the command pipe. */ for (;;) { FD_ZERO(&reads); FD_SET(0, &reads); FD_SET(data, &reads); if (select(data + 1, &reads, NULL, NULL, NULL) <= 0) { if (errno == EINTR && got_sigwinch) { got_sigwinch = 0; term_resize(); } continue; } if (FD_ISSET(0, &reads)) { if ((nread = read(0, buffer, sizeof(buffer))) > 0) write(data, buffer, nread); else my_exit(3); } if (FD_ISSET(data, &reads)) { if ((nread = read(data, buffer, sizeof(buffer))) > 0) write(0, buffer, nread); else my_exit(4); } } my_exit(8); }
/** * signals_init - install our signal handlers * * This installs all of our signal handlers. * It also maintains a copy of old signal handlers * when the rep library is used, so we can notify * the library of events. * * Make sure to call me once, after the reo library initilization * but before we do anything. **/ void signals_init(void) { my_signal(SIGBUS, sig_coredump); old_segv = my_signal(SIGSEGV, sig_coredump); my_signal(SIGQUIT, SIG_IGN); my_signal(SIGPIPE, SIG_IGN); my_signal(SIGHUP, sig_quit_irc); my_signal(SIGTERM, sig_quit_irc); my_signal(SIGALRM, sig_nothing); my_signal(SIGCONT, sig_continue); my_signal(SIGWINCH, sig_refresh_screen); old_sigint = my_signal(SIGINT, sig_int); old_sigchild = my_signal(SIGCHLD, sig_child); /* do this test now, instead of in each of the signal handlers. */ if (!VALID_SIGHAND(old_segv)) old_segv = sig_nothing; if (!VALID_SIGHAND(old_sigint)) old_sigint = sig_nothing; if (!VALID_SIGHAND(old_sigchild)) old_sigchild = sig_nothing; }
RcppExport SEXP FitPhasingBurst(SEXP R_signal, SEXP R_flowCycle, SEXP R_read_sequence, SEXP R_phasing, SEXP R_burstFlows, SEXP R_maxEvalFlow, SEXP R_maxSimFlow) { SEXP ret = R_NilValue; char *exceptionMesg = NULL; try { Rcpp::NumericMatrix signal(R_signal); Rcpp::NumericMatrix phasing(R_phasing); // Standard phasing parameters string flowCycle = Rcpp::as<string>(R_flowCycle); Rcpp::StringVector read_sequences(R_read_sequence); Rcpp::NumericVector phasing_burst(R_burstFlows); Rcpp::NumericVector max_eval_flow(R_maxEvalFlow); Rcpp::NumericVector max_sim_flow(R_maxSimFlow); int window_size = 38; // For normalization ion::FlowOrder flow_order(flowCycle, flowCycle.length()); unsigned int num_flows = flow_order.num_flows(); unsigned int num_reads = read_sequences.size(); // Containers to store results Rcpp::NumericVector null_fit(num_reads); Rcpp::NumericMatrix null_prediction(num_reads, num_flows); Rcpp::NumericVector best_fit(num_reads); Rcpp::NumericVector best_ie_value(num_reads); Rcpp::NumericMatrix best_prediction(num_reads, num_flows); BasecallerRead bc_read; DPTreephaser dpTreephaser(flow_order); DPPhaseSimulator PhaseSimulator(flow_order); vector<double> cf_vec(num_flows, 0.0); vector<double> ie_vec(num_flows, 0.0); vector<double> dr_vec(num_flows, 0.0); // IE Burst Estimation Loop for (unsigned int iRead=0; iRead<num_reads; iRead++) { // Set read object vector<float> my_signal(num_flows); for (unsigned int iFlow=0; iFlow<num_flows; iFlow++) my_signal.at(iFlow) = signal(iRead, iFlow); bc_read.SetData(my_signal, num_flows); string my_sequence = Rcpp::as<std::string>(read_sequences(iRead)); // Default phasing as baseline double my_best_fit, my_best_ie; double base_cf = (double)phasing(iRead, 0); double base_ie = (double)phasing(iRead, 1); double base_dr = (double)phasing(iRead, 2); int burst_flow = (int)phasing_burst(iRead); vector<float> my_best_prediction; cf_vec.assign(num_flows, base_cf); dr_vec.assign(num_flows, base_dr); int my_max_flow = min((int)num_flows, (int)max_sim_flow(iRead)); int my_eval_flow = min(my_max_flow, (int)max_eval_flow(iRead)); PhaseSimulator.SetBaseSequence(my_sequence); PhaseSimulator.SetMaxFlows(my_max_flow); PhaseSimulator.SetPhasingParameters_Basic(base_cf, base_ie, base_dr); PhaseSimulator.UpdateStates(my_max_flow); PhaseSimulator.GetPredictions(bc_read.prediction); dpTreephaser.WindowedNormalize(bc_read, (my_eval_flow/window_size), window_size, true); my_best_ie = base_ie; my_best_prediction = bc_read.prediction; my_best_fit = 0; for (int iFlow=0; iFlow<my_eval_flow; iFlow++) { double residual = bc_read.raw_measurements.at(iFlow) - bc_read.prediction.at(iFlow); my_best_fit += residual*residual; } for (unsigned int iFlow=0; iFlow<num_flows; iFlow++) null_prediction(iRead, iFlow) = bc_read.prediction.at(iFlow); null_fit(iRead) = my_best_fit; // Make sure that there are enough flows to fit a burst if (burst_flow < my_eval_flow-10) { int num_steps = 0; double step_size = 0.0; double step_start = 0.0; double step_end = 0.0; // Brute force phasing burst value estimation using grid search, crude first, then refine for (unsigned int iIteration = 0; iIteration<3; iIteration++) { switch(iIteration) { case 0: step_size = 0.05; step_end = 0.8; break; case 1: step_end = (floor(my_best_ie / step_size)*step_size) + step_size; step_start = max(0.0, (step_end - 2.0*step_size)); step_size = 0.01; break; default: step_end = (floor(my_best_ie / step_size)*step_size) + step_size; step_start = max(0.0, step_end - 2*step_size); step_size = step_size / 10; } num_steps = 1+ ((step_end - step_start) / step_size); for (int iPhase=0; iPhase <= num_steps; iPhase++) { double try_ie = step_start+(iPhase*step_size); ie_vec.assign(num_flows, try_ie); PhaseSimulator.SetBasePhasingParameters(burst_flow, cf_vec, ie_vec, dr_vec); PhaseSimulator.UpdateStates(my_max_flow); PhaseSimulator.GetPredictions(bc_read.prediction); dpTreephaser.WindowedNormalize(bc_read, (my_eval_flow/window_size), window_size, true); double my_fit = 0.0; for (int iFlow=burst_flow+1; iFlow<my_eval_flow; iFlow++) { double residual = bc_read.raw_measurements.at(iFlow) - bc_read.prediction.at(iFlow); my_fit += residual*residual; } if (my_fit < my_best_fit) { my_best_fit = my_fit; my_best_ie = try_ie; my_best_prediction = bc_read.prediction; } } } } // Set output information for this read best_fit(iRead) = my_best_fit; best_ie_value(iRead) = my_best_ie; for (unsigned int iFlow=0; iFlow<num_flows; iFlow++) best_prediction(iRead, iFlow) = my_best_prediction.at(iFlow); } ret = Rcpp::List::create(Rcpp::Named("null_fit") = null_fit, Rcpp::Named("null_prediction") = null_prediction, Rcpp::Named("burst_flow") = phasing_burst, Rcpp::Named("best_fit") = best_fit, Rcpp::Named("best_ie_value") = best_ie_value, Rcpp::Named("best_prediction") = best_prediction); } catch(std::exception& ex) { forward_exception_to_r(ex); } catch(...) { ::Rf_error("c++ exception (unknown reason)"); } if(exceptionMesg != NULL) Rf_error(exceptionMesg); return ret; }
/* ------------------------------------------------------------------- * main() * Entry point into Iperf * * sets up signal handlers * initialize global locks and conditions * parses settings from environment and command line * starts up server or client thread * waits for all threads to complete * ------------------------------------------------------------------- */ #ifdef __cplusplus extern "C" #endif /* __cplusplus */ int IPERF_MAIN( int argc, char **argv ) { #ifdef NO_EXIT should_exit = 0; #endif /* NO_EXIT */ #ifdef IPERF_DEBUG debug_init(); #endif /* IPERF_DEBUG */ #ifndef NO_INTERRUPTS #ifdef WIN32 setsigalrmfunc(call_sigalrm); #endif /* WIN32 */ // Set SIGTERM and SIGINT to call our user interrupt function my_signal( SIGTERM, Sig_Interupt ); my_signal( SIGINT, Sig_Interupt ); my_signal( SIGALRM, Sig_Interupt ); #ifndef WIN32 // Ignore broken pipes signal(SIGPIPE,SIG_IGN); #else // Start winsock WORD wVersionRequested; WSADATA wsaData; // Using MAKEWORD macro, Winsock version request 2.2 wVersionRequested = MAKEWORD(2, 2); int rc = WSAStartup( wVersionRequested, &wsaData ); WARN_errno( rc == SOCKET_ERROR, ( "WSAStartup failed.\n" ) ); if (rc != 0) { fprintf(stderr, "The Winsock DLL was not found!\n"); return 1; } /* * Confirm that the WinSock DLL supports 2.2. Note that if the DLL supports * versions greater than 2.2 in addition to 2.2, it will still return 2.2 in * wVersion since that is the version we requested. */ if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2 ) { /* Tell the user that we could not find a usable WinSock DLL. */ fprintf(stderr, "The DLL does not support the Winsock version %u.%u!\n", LOBYTE(wsaData.wVersion),HIBYTE(wsaData.wVersion)); WSACleanup(); return 1; } // Tell windows we want to handle our own signals SetConsoleCtrlHandler( sig_dispatcher, true ); #endif /* WIN32 */ #endif /* NO_INTERRUPTS */ // Initialize global mutexes and conditions IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Initializing report condition.\n" ) ); Condition_Initialize ( &ReportCond ); IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Initializing report done condition.\n" ) ); Condition_Initialize ( &ReportDoneCond ); IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Initializing group condition mutex.\n" ) ); Mutex_Initialize( &groupCond ); IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Initializing clients mutex.\n" ) ); Mutex_Initialize( &clients_mutex ); // Initialize the thread subsystem IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Initializing the thread subsystem.\n" ) ); thread_init( ); // Initialize the interrupt handling thread to 0 sThread = thread_zeroid(); #ifndef NO_EXIT // perform any cleanup when quitting Iperf atexit( cleanup ); #endif /* NO_EXIT */ // Allocate the "global" settings thread_Settings *ext_gSettings = (thread_Settings*) malloc( sizeof( thread_Settings ) ); FAIL( ext_gSettings == NULL, ( "Unable to allocate memory for thread_Settings ext_gSettings.\n" ), NULL ); IPERF_DEBUGF( MEMALLOC_DEBUG, IPERF_MEMALLOC_MSG( ext_gSettings, sizeof( thread_Settings ) ) ); // Initialize settings to defaults Settings_Initialize( ext_gSettings ); #ifndef NO_ENVIRONMENT // read settings from environment variables Settings_ParseEnvironment( ext_gSettings ); #endif /* NO_ENVIORNMENT */ // read settings from command-line parameters Settings_ParseCommandLine( argc, argv, ext_gSettings ); #ifdef NO_EXIT if (should_exit) { IPERF_DEBUGF( MEMFREE_DEBUG | IPERF_DBG_TRACE, IPERF_MEMFREE_MSG( ext_gSettings ) ); FREE_PTR( ext_gSettings ); IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report condition.\n" ) ); Condition_Destroy( &ReportCond ); IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report done condition.\n" ) ); Condition_Destroy( &ReportDoneCond ); IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying group condition mutex.\n" ) ); Mutex_Destroy( &groupCond ); IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying clients mutex.\n" ) ); Mutex_Destroy( &clients_mutex ); return 0; } #endif /* NO_EXIT */ // Check for either having specified client or server if ( ext_gSettings->mThreadMode == kMode_Client || ext_gSettings->mThreadMode == kMode_Listener ) { #ifdef WIN32 #ifndef NO_DAEMON // Start the server as a daemon // Daemon mode for non-windows in handled // in the listener_spawn function if ( isDaemon( ext_gSettings ) ) { CmdInstallService(argc, argv); return 0; } #endif /* NO_DAEMON */ #ifndef NO_SERVICE // Remove the Windows service if requested if ( isRemoveService( ext_gSettings ) ) { // remove the service if ( CmdRemoveService() ) { fprintf(stderr, "IPerf Service is removed.\n"); return 0; } } #endif /* NO_SERVICE */ #endif /* WIN32 */ // initialize client(s) if ( ext_gSettings->mThreadMode == kMode_Client ) { IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | IPERF_DBG_TRACE, ( "Initializing client(s)...\n" ) ); client_init( ext_gSettings ); } #ifdef HAVE_THREAD // start up the reporter and client(s) or listener thread_Settings *into = NULL; // Create the settings structure for the reporter thread IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | REPORTER_DEBUG | IPERF_DBG_TRACE, ( "Creating the settings structure for the reporter thread.\n" ) ); Settings_Copy( ext_gSettings, &into ); into->mThreadMode = kMode_Reporter; // Have the reporter launch the client or listener IPERF_DEBUGF( CLIENT_DEBUG | LISTENER_DEBUG | IPERF_DBG_TRACE, ( "Setting the reporter to launch the client or listener before launching itself.\n" ) ); into->runNow = ext_gSettings; // Start all the threads that are ready to go IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Starting all the threads...\n" ) ); thread_start( into ); #else // No need to make a reporter thread because we don't have threads IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Starting iperf in a single thread...\n" ) ); thread_start( ext_gSettings ); #endif /* HAVE_THREAD */ } else { // neither server nor client mode was specified // print usage and exit #ifdef WIN32 // In Win32 we also attempt to start a previously defined service // Starting in 2.0 to restart a previously defined service // you must call iperf with "iperf -D" or using the environment variable SERVICE_TABLE_ENTRY dispatchTable[] = { { TEXT((char *) SZSERVICENAME), (LPSERVICE_MAIN_FUNCTION)service_main}, { NULL, NULL} }; #ifndef NO_DAEMON // Only attempt to start the service if "-D" was specified if ( !isDaemon(ext_gSettings) || // starting the service by SCM, there is no arguments will be passed in. // the arguments will pass into Service_Main entry. !StartServiceCtrlDispatcher(dispatchTable) ) // If the service failed to start then print usage #endif /* NO_DAEMON */ #endif /* WIN32 */ fprintf( stderr, usage_short, argv[0], argv[0] ); return 0; } // wait for other (client, server) threads to complete // IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Waiting for other (client, server) threads to complete...\n" ) ); // thread_joinall(); #ifdef NO_EXIT /* We can't run the atexit function */ #ifdef WIN32 // Shutdown Winsock WSACleanup(); #endif /* WIN32 */ // clean up the list of clients Iperf_destroy ( &clients ); // shutdown the thread subsystem IPERF_DEBUGF( THREAD_DEBUG | IPERF_DBG_TRACE, ( "Deinitializing the thread subsystem.\n" ) ); IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report condition.\n" ) ); Condition_Destroy( &ReportCond ); IPERF_DEBUGF( CONDITION_DEBUG | IPERF_DBG_TRACE, ( "Destroying report done condition.\n" ) ); Condition_Destroy( &ReportDoneCond ); IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying group condition mutex.\n" ) ); Mutex_Destroy( &groupCond ); IPERF_DEBUGF( MUTEX_DEBUG | IPERF_DBG_TRACE, ( "Destroying clients mutex.\n" ) ); Mutex_Destroy( &clients_mutex ); #ifdef IPERF_DEBUG debug_init(); #endif /* IPERF_DEBUG */ #endif /* NO_EXIT */ // all done! IPERF_DEBUGF( IPERF_DBG_TRACE | IPERF_DBG_STATE, ( "Done!\n" ) ); return 0; } // end main