当前位置: 首页>>代码示例>>C++>>正文


C++ sigaction函数代码示例

本文整理汇总了C++中sigaction函数的典型用法代码示例。如果您正苦于以下问题:C++ sigaction函数的具体用法?C++ sigaction怎么用?C++ sigaction使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了sigaction函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: main

/* main function */
int main()
{
	int ret;
	pthread_t child;


	struct sigaction sa;

	/* Initialize output */
	output_init();

	/* Set the signal handler */
	sa.sa_flags = SA_RESTART;
	sa.sa_handler = handler;
	ret = sigemptyset( &sa.sa_mask );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to empty signal set" );
	}

	/* Install the signal handler for SIGNAL */
	ret = sigaction( SIGNAL, &sa, 0 );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to set signal handler" );
	}

	/* Initialize the semaphore */
	ret = sem_init( &sem, 0, 0 );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to init a semaphore" );
	}

	/* Create the child thread */
	ret = pthread_create( &child, NULL, threaded, NULL );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to create a child thread" );
	}

	/* Let the child thread enter the wait routine...
	  we use sched_yield as there is no certain way to test that the child
	  is waiting for the semaphore... */
	sched_yield();

	sched_yield();

	sched_yield();

	/* Ok, now kill the child */
	ret = pthread_kill( child, SIGNAL );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to kill the child thread" );
	}

	/* wait that the child receives the signal */
	while ( !caught )
		sched_yield();

	/* Now let the child run and terminate */
	ret = sem_post( &sem );

	if ( ret != 0 )
	{
		UNRESOLVED( errno, "Failed to post the semaphore" );
	}

	ret = pthread_join( child, NULL );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to join the thread" );
	}

	/* terminate */
	ret = sem_destroy( &sem );

	if ( ret != 0 )
	{
		UNRESOLVED( ret, "Failed to destroy the semaphore" );
	}


	/* Test passed */
#if VERBOSE > 0

	output( "Test passed\n" );

#endif

	PASSED;
}
开发者ID:crystax,项目名称:android-vendor-openpts,代码行数:100,代码来源:16-8.c

示例2: control_loop_setup

int control_loop_setup( int ms_period, int ctrl_gain, int ubisense,
                        double *offset_r, double *offset_p )
{
    struct sigaction act;

    /* initialize global variables */
    running             = 1;
    period              = ms_period / 1000.0;
    us_period           = ms_period * 1000;
    pos_ctrl_gain       = ctrl_gain;
    ubisense_enabled    = ubisense;
    heli_state          = HELI_STATE_SHUTDOWN;
    heli_mode           = HELI_MODE_POS_CTRL;
    heli_settled        = 1;
    yaw_wn_imu          = 0;
    yaw_wn_cmd          = 0;
    new_data_x          = 0;
    new_data_y          = 0;
    new_data_z          = 0;
    offset_roll         = offset_r;
    offset_pitch        = offset_p;
    cmd_roll            = 0;
    cmd_pitch           = 0;
    next_period         = 0;
    motor_speed_revving = 0;
    motor_speed_liftoff = 0;
    act.sa_handler      = signal_handler;
	act.sa_handler      = int_handler;

    /* initialize signal handlers */
    if( sigaction( SIGUSR1, &act, NULL ) || sigaction( SIGINT, &act, NULL ) )
    {
        perror( "sigaction" );
    }

    /* initialize filter objects */
    outlier_filter_init( &cof_out_x,     "OUT_X",     COF_MDIFF_POS, COF_LIMIT_POS );
    outlier_filter_init( &cof_out_y,     "OUT_Y",     COF_MDIFF_POS, COF_LIMIT_POS );
    iir_lp_filter_init ( &iir_acc_x,     "ACC_X",     IIR_GAIN_LACC );
    iir_lp_filter_init ( &iir_acc_y,     "ACC_Y",     IIR_GAIN_LACC );
    iir_lp_filter_init ( &iir_acc_z,     "ACC_Z",     IIR_GAIN_LACC );
    iir_lp_filter_init ( &iir_cmd_roll,  "CMD_Roll",  IIR_GAIN_RCMD );
    iir_lp_filter_init ( &iir_cmd_pitch, "CMD_Pitch", IIR_GAIN_RCMD );
    iir_lp_filter_init ( &iir_cmd_yaw,   "CMD_Yaw",   IIR_GAIN_RCMD );
    iir_lp_filter_init ( &iir_cmd_z,     "CMD_Z",     IIR_GAIN_RCMD );
    average_filter_init( &avg_bmu_maps,  "BMU_MAPS",  AVG_SIZE_MAPS );
    median_filter_init ( &med_bmu_temp,  "BMU_Temp",  MED_SIZE_TEMP );
    median_filter_init ( &med_bmu_batt,  "BMU_Batt",  MED_SIZE_BATT );
    attitude_ekf_init  ( &ekf_att_roll,  "ATT_Roll",  EKF_ATT_STD_E, EKF_ATT_STD_W, EKF_ATT_PH_SH, period );
    attitude_ekf_init  ( &ekf_att_pitch, "ATT_Pitch", EKF_ATT_STD_E, EKF_ATT_STD_W, EKF_ATT_PH_SH, period );
    attitude_ekf_init  ( &ekf_att_yaw,   "ATT_Yaw",   EKF_ATT_STD_E, EKF_ATT_STD_W, EKF_ATT_PH_SH, period );
    position_ekf_init  ( &ekf_pos_x,     "POS_X",     EKF_POS_STD_P, EKF_POS_STD_V, EKF_POS_STD_A, period );
    position_ekf_init  ( &ekf_pos_y,     "POS_Y",     EKF_POS_STD_P, EKF_POS_STD_V, EKF_POS_STD_A, period );
    position_ekf_init  ( &ekf_pos_z,     "POS_Z",     EKF_POS_STD_P, EKF_POS_STD_V, EKF_POS_STD_A, period );

    /* initialize controller objects */
    controller_init    ( &ctrl_roll,     "Roll",      CTRL_PIDD_DEF, period );
    controller_init    ( &ctrl_pitch,    "Pitch",     CTRL_PIDD_DEF, period );
    controller_init    ( &ctrl_yaw,      "Yaw",       CTRL_PIDD_DEF, period );
    controller_init    ( &ctrl_x,        "X",         CTRL_PIDD_X_Y, period );
    controller_init    ( &ctrl_y,        "Y",         CTRL_PIDD_X_Y, period );
    controller_init    ( &ctrl_z,        "Z",         CTRL_PIDD_DEF, period );

    /* initialize transformations */
    transformation_init( );

    /* clear data structures */
    memset( &command_data,  0, sizeof( command_data ) );
    memset( &javiator_data, 0, sizeof( javiator_data ) );
    memset( &sensor_data,   0, sizeof( sensor_data ) );
    memset( &motor_signals, 0, sizeof( motor_signals ) );
    memset( &motor_offsets, 0, sizeof( motor_offsets ) );
    memset( &trace_data,    0, sizeof( trace_data ) );

    return( 0 );
}
开发者ID:cksystemsgroup,项目名称:JNavigator,代码行数:76,代码来源:control_loop.c

示例3: main

int main( int argc, char *argv[] )
{
    int port = LISTEN_PORT;		/* set the port default value as PORT */
    int listen_fd;			/* define server listen fd */
    int conn_fd;			/* define connect fd */
    struct sockaddr_in server_addr, client_addr;
    socklen_t client_addr_len;
    char str[32];
    char buf[32];
    int total = 0, i, j;
    int ret;

    struct sigaction newact, oldact;

    /* set our handler, save the old one */
    newact.sa_handler = sig_int;
    newact.sa_flags = 0;
    sigaction(SIGINT, &newact, &oldact );

    /* set our handler, save the old one */
    newact.sa_handler = sig_pipe;
    newact.sa_flags = 0;
    sigaction(SIGPIPE, &newact, &oldact );

    /* get the listen port from command line argv[1] */
    if( argv[1] )
        port = atoi( argv[1] );

    printf( "server begin at port: %d \n", port );

    /* create socket and listen */
    listen_fd = socket( AF_INET,SOCK_STREAM, 0);

    /* fill in the struct */
    bzero( &server_addr, sizeof(server_addr) );
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = htonl( INADDR_ANY );
    server_addr.sin_port = htons( port );

    /* bind server listen port */
    ret = bind( listen_fd, (struct sockaddr *)&server_addr, sizeof(server_addr) );
    if( ret < 0 )
        printf( "server bind error !\n" );

    /* server begin to listen */
    listen( listen_fd, 8 );
    printf( "Accepting connections: %d \n", port );

    client_addr_len = sizeof( client_addr );
    conn_fd = accept( listen_fd, (struct sockaddr *)&client_addr, &client_addr_len );

    printf( "client is connected from %s:%d! \n",
            inet_ntop(AF_INET, &client_addr.sin_addr, str, sizeof(str)),
            ntohs(client_addr.sin_port) );

    while( 1 )
    {
        if( (ret = read(conn_fd, buf, 32)) > 0 )
        {
            buf[ret] = '\0';
            printf( "From Client: %s", buf );
            printf( "Write To Client: %s \n", buf );
            write( conn_fd, buf, strlen(buf) );
        }
        else if( ret == 0 )
        {
            printf( "client socket is closed! \n" );
            close( conn_fd );
            exit( 0 );
        }
    }

    return 0;
}
开发者ID:guolilong2012,项目名称:study,代码行数:74,代码来源:server.c

示例4: snprintf

  void SignalHandler::setup_default_handlers(std::string path) {
#ifndef RBX_WINDOWS
    report_path[0] = 0;

    // Calculate the report_path
    if(path.rfind("/") == std::string::npos) {
      if(char* home = getenv("HOME")) {
        snprintf(report_path, PATH_MAX, "%s/.rbx", home);

        pid_t pid = getpid();

        bool use_dir = false;
        struct stat s;
        if(stat(report_path, &s) != 0) {
          if(mkdir(report_path, S_IRWXU) == 0) use_dir = true;
        } else if(S_ISDIR(s.st_mode)) {
          use_dir = true;
        }

        if(use_dir) {
          snprintf(report_path + strlen(report_path), PATH_MAX, "/%s_%d",
                   path.c_str(), pid);
        } else {
          snprintf(report_path, PATH_MAX, "%s/.%s_%d", home, path.c_str(), pid);
        }
      }
    }

    if(!report_path[0]) {
      strncpy(report_path, path.c_str(), PATH_MAX-1);
    }

    // Test that we can actually use this path.
    int fd = open(report_path, O_RDONLY | O_CREAT, 0666);
    if(!fd) {
      char buf[RBX_STRERROR_BUFSIZE];
      char* err = RBX_STRERROR(errno, buf, RBX_STRERROR_BUFSIZE);
      std::cerr << "Unable to use " << report_path << " for crash reports.\n";
      std::cerr << "Unable to open path: " << err << "\n";

      // Don't use the home dir path even, just use stderr
      report_path[0] = 0;
    } else {
      close(fd);
      unlink(report_path);
    }

    // Get the machine info.
    uname(&machine_info);

    struct sigaction action;
    action.sa_handler = null_func;
    action.sa_flags = 0;
    sigfillset(&action.sa_mask);
    sigaction(SIGVTALRM, &action, NULL);

    // Some extensions expect SIGALRM to be defined, because MRI does.
    // We'll just use a noop for it.
    action.sa_handler = null_func;
    sigaction(SIGALRM, &action, NULL);

    // Ignore sigpipe.
    action.sa_handler = SIG_IGN;
    sigaction(SIGPIPE, &action, NULL);

#ifdef USE_EXECINFO
    // If we have execinfo, setup some crash handlers
    if(!getenv("DISABLE_SEGV")) {
      action.sa_handler = segv_handler;
      sigaction(SIGSEGV, &action, NULL);
      sigaction(SIGBUS,  &action, NULL);
      sigaction(SIGILL,  &action, NULL);
      sigaction(SIGFPE,  &action, NULL);
      sigaction(SIGABRT, &action, NULL);
    }
#endif  // USE_EXEC_INFO
#else
    signal(SIGTERM, quit_handler);
#endif  // ifndef RBX_WINDOWS
  }
开发者ID:LTechnologies,项目名称:rubinius,代码行数:80,代码来源:signal.cpp

示例5: main

int main(int argc, char *argv[]) {
	struct sigaction act;
	int argn = 1, ret;

	{
		const char *home = getenv("HOME");
		if (home) {
			char *conffile = xmalloc(strlen(home) + sizeof(CONFIG_FILE) + 2);
			strcpy(conffile, home);
			strcat(conffile, "/" CONFIG_FILE);
			xconfig_parse_file(evilwm_options, conffile);
			free(conffile);
		}
	}
	ret = xconfig_parse_cli(evilwm_options, argc, argv, &argn);
	if (ret == XCONFIG_MISSING_ARG) {
		fprintf(stderr, "%s: missing argument to `%s'\n", argv[0], argv[argn]);
		exit(1);
	} else if (ret == XCONFIG_BAD_OPTION) {
		if (0 == strcmp(argv[argn], "-h")
				|| 0 == strcmp(argv[argn], "--help")) {
			helptext();
			exit(0);
#ifdef STDIO
		} else if (0 == strcmp(argv[argn], "-V")
				|| 0 == strcmp(argv[argn], "--version")) {
			LOG_INFO("evilwm version " VERSION "\n");
			exit(0);
#endif
		} else {
			helptext();
			exit(1);
		}
	}

	if (opt_grabmask1) grabmask1 = parse_modifiers(opt_grabmask1);
	if (opt_grabmask2) grabmask2 = parse_modifiers(opt_grabmask2);
	if (opt_altmask) altmask = parse_modifiers(opt_altmask);

	wm_exit = 0;
	act.sa_handler = handle_signal;
	sigemptyset(&act.sa_mask);
	act.sa_flags = 0;
	sigaction(SIGTERM, &act, NULL);
	sigaction(SIGINT, &act, NULL);
	sigaction(SIGHUP, &act, NULL);

	setup_display();

	event_main_loop();

	/* Quit Nicely */
	while (clients_stacking_order)
		remove_client(clients_stacking_order->data);
	XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
	if (font) XFreeFont(dpy, font);
	{
		int i;
		for (i = 0; i < num_screens; i++) {
			ewmh_deinit_screen(&screens[i]);
			XFreeGC(dpy, screens[i].invert_gc);
			XInstallColormap(dpy, DefaultColormap(dpy, i));
		}
	}
	free(screens);
	XCloseDisplay(dpy);

	return 0;
}
开发者ID:yugecin,项目名称:evilwm,代码行数:69,代码来源:main.c

示例6: main

int
main(int argc, char *argv[])
{
    const int STACK_SIZE = 65536;       /* Stack size for cloned child */
    char *stack;                        /* Start of stack buffer area */
    char *stackTop;                     /* End of stack buffer area */
    int flags;                          /* Flags for cloning child */
    ChildParams cp;                     /* Passed to child function */
    const mode_t START_UMASK = S_IWOTH; /* Initial umask setting */
    struct sigaction sa;
    char *p;
    int status;
    ssize_t s;
    pid_t pid;

    printf("Parent: PID=%ld PPID=%ld\n", (long) getpid(), (long) getppid());

    /* Set up an argument structure to be passed to cloned child, and
       set some process attributes that will be modified by child */

    cp.exitStatus = 22;                 /* Child will exit with this status */

    umask(START_UMASK);                 /* Initialize umask to some value */
    cp.umask = S_IWGRP;                 /* Child sets umask to this value */

    cp.fd = open("/dev/null", O_RDWR);  /* Child will close this fd */
    if (cp.fd == -1)
        errExit("open");

    cp.signal = SIGTERM;                /* Child will change disposition */
    if (signal(cp.signal, SIG_IGN) == SIG_ERR)
        errExit("signal");

    /* Initialize clone flags using command-line argument (if supplied) */

    flags = 0;
    if (argc > 1) {
        for (p = argv[1]; *p != '\0'; p++) {
            if      (*p == 'd') flags |= CLONE_FILES;
            else if (*p == 'f') flags |= CLONE_FS;
            else if (*p == 's') flags |= CLONE_SIGHAND;
            else if (*p == 'v') flags |= CLONE_VM;
            else usageError(argv[0]);
        }
    }

    /* Allocate stack for child */

    stack = malloc(STACK_SIZE);
    if (stack == NULL)
        errExit("malloc");
    stackTop = stack + STACK_SIZE;  /* Assume stack grows downward */

    /* Establish handler to catch child termination signal */

    if (CHILD_SIG != 0) {
        sigemptyset(&sa.sa_mask);
        sa.sa_flags = SA_RESTART;
        sa.sa_handler = grimReaper;
        if (sigaction(CHILD_SIG, &sa, NULL) == -1)
            errExit("sigaction");
    }

    /* Create child; child commences execution in childFunc() */

    if (clone(childFunc, stackTop, flags | CHILD_SIG, &cp) == -1)
        errExit("clone");

    /* Parent falls through to here. Wait for child; __WCLONE option is
       required for child notifying with signal other than SIGCHLD. */

    pid = waitpid(-1, &status, (CHILD_SIG != SIGCHLD) ? __WCLONE : 0);
    if (pid == -1)
        errExit("waitpid");

    printf("    Child PID=%ld\n", (long) pid);
    printWaitStatus("    Status: ", status);

    /* Check whether changes made by cloned child have affected parent */

    printf("Parent - checking process attributes:\n");
    if (umask(0) != START_UMASK)
        printf("    umask has changed\n");
    else
        printf("    umask has not changed\n");

    s = write(cp.fd, "Hello world\n", 12);
    if (s == -1 && errno == EBADF)
        printf("    file descriptor %d has been closed\n", cp.fd);
    else if (s == -1)
        printf("    write() on file descriptor %d failed (%s)\n",
                cp.fd, strerror(errno));
    else
        printf("    write() on file descriptor %d succeeded\n", cp.fd);

    if (sigaction(cp.signal, NULL, &sa) == -1)
        errExit("sigaction");
    if (sa.sa_handler != SIG_IGN)
        printf("    signal disposition has changed\n");
    else
//.........这里部分代码省略.........
开发者ID:Heuristack,项目名称:Productivity,代码行数:101,代码来源:demo_clone.c

示例7: main

int main(int argc, char** argv)
{
  char *buffer = NULL;
  int portno = 0, stop, optval;
  socklen_t clilen;
  struct sockaddr_in serv_addr, cli_addr;
  struct sigaction action_CHLD;
  struct sigaction action_ALRM;

  /* Preliminary signal configuration:
   * SIGCHLD and SIGALRM are used with different handler
   * configure each handler to mask the other signal during it's process
   * Note: within a handler called upon a signal SIGX, the SIGX signal is
   * automatically de-activated.
   */

  sigemptyset(&block_sigs);
  sigaddset(&block_sigs, SIGCHLD);
  sigaddset(&block_sigs, SIGALRM);

  action_CHLD.sa_flags = SA_RESTART;
  action_CHLD.sa_handler = SIGCHLD_handler;
  sigemptyset(&(action_CHLD.sa_mask));
  sigaddset(&(action_CHLD.sa_mask), SIGALRM);

  action_ALRM.sa_flags = SA_RESTART;
  action_ALRM.sa_handler = SIGALRM_handler;
  sigemptyset(&(action_ALRM.sa_mask));
  sigaddset(&(action_ALRM.sa_mask), SIGCHLD);

  PointerList_Create(&apps, 0);
  if (NULL == apps)
    err_exit("PointerList_Create");

  /* Command line arguments Parsing
   * Options
   * a : privileged app path
   * w : privileged app working directory
   * v : user id to use to start privileged app
   * h : group id to use to start privileged app
   * p : TCP port to receive commands
   * u : user id to use to start regular apps
   * g : group id to use to start regular apps
   * n : nice value (process priority) for regular apps
   */
  char* init_app = NULL;
  char* init_app_wd = NULL;
  app_t* privileged_app = NULL;
  int opt;
  char useropt_given = 0;
  char grpopt_given = 0;
  //optarg is set by getopt
  while ((opt = getopt(argc, argv, "a:w:v:h:p:u:g:n:")) != -1)
  {
    switch (opt)
    {
      case 'a':
        init_app = optarg;
        SWI_LOG("APPMON", DEBUG, "Command line arguments parsing: init_app %s\n", init_app);
        break;
      case 'w':
        init_app_wd = optarg;
        SWI_LOG("APPMON", DEBUG, "Command line arguments parsing: init_app_wd %s\n", init_app_wd);
        break;
      case 'p':
        parse_arg_integer(optarg, &portno, "Command line arguments parsing: bad format for port argument");
        SWI_LOG("APPMON", DEBUG, "Command line arguments parsing: port =%d\n", portno);
        if (portno > UINT16_MAX)
        {
          err_exit("Command line arguments parsing: bad value for port, range=[0, 65535]");
        }
        break;
      case 'u':
        useropt_given = 1; //used to set default value after cmd line option parsing
        get_uid_option(&uid);
        break;
      case 'v':
        get_uid_option(&puid);
        break;
      case 'g':
        grpopt_given = 1; //used to set default value after cmd line option parsing
        get_gid_option(&gid);
        break;
      case 'h':
        get_gid_option(&pgid);
        break;
      case 'n':
        parse_arg_integer(optarg, &app_priority,
            "Command line arguments parsing: app process priority must be an integer");
        if (19 < app_priority || -20 > app_priority)
        {
          err_exit("Command line arguments parsing: app process priority must be between -20 and 19");
        }
        SWI_LOG("APPMON", DEBUG, "Command line arguments parsing: nice increment =%d\n", app_priority);
        break;
      default: /* '?' */
        SWI_LOG("APPMON", ERROR, "Command line arguments parsing: unknown argument\n");
        break;
    }

//.........这里部分代码省略.........
开发者ID:WeiY,项目名称:mihini-repo,代码行数:101,代码来源:appmon_daemon.c

示例8: main

/**
 * Principal
 */
int main(int argc, char * argv[]) {
  
  //sockfd refere-se à escuta, new_fd a novas conexoes
  int sockfd, new_fd;  			
  struct addrinfo hints, *servinfo, *p;

  //informacao de endereco dos conectores
  struct sockaddr_storage their_addr; 	

  socklen_t sin_size;
  struct sigaction sa;
  int yes=1;
  char s[INET6_ADDRSTRLEN];
  int rv;
  int ativo; // Booleano que indica se a conexao deve continuar ativa
  
  // Vetor que contera a opcao do cliente (mais o id do filme, se for o
  // caso)
  char opt[4];		                

  loadBooksFromDB();
    
  memset(&hints, 0, sizeof hints);
  hints.ai_family = AF_UNSPEC;
  hints.ai_socktype = SOCK_STREAM; // Stream socket
  hints.ai_flags = AI_PASSIVE;
  
  if ((rv = getaddrinfo(NULL, PORT, &hints, &servinfo)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(rv));
    return 1;
  }
  
  // Percorre a lista ligada e realiza 'bind' ao primeiro que for possivel
  // Cria todos os file descriptors dos sockets, dando nome a eles
  for(p = servinfo; p != NULL; p = p->ai_next) {

    //Função SOCKET: cria um socket, dando acesso ao serviço da camada de transporte
    if ((sockfd = socket(p->ai_family, p->ai_socktype,p->ai_protocol)) == -1) {
      perror("server: socket");
      continue;
    }
    
    if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) {
      perror("setsockopt");
      exit(1);
    }
    
    //Função bind: atribui um nome ao socket
    if (bind(sockfd, p->ai_addr, p->ai_addrlen) == -1) {
      close(sockfd);
      perror("server: bind");
      continue;
    }
    
    break;
  }
  
  // Debug de erro
  if (p == NULL)  {
    fprintf(stderr, "servidor: falha ao realizar 'bind'\n");
    return 2;
  }
  
  // Necessario devido à chamada 'getaddrinfo' acima
  freeaddrinfo(servinfo); 
  
  // Anuncia que está apto para receber conexões
  if (listen(sockfd, BACKLOG) == -1) {
    perror("listen");
    exit(1);
  }
  
  sa.sa_handler = sigchld_handler;
  sigemptyset(&sa.sa_mask);
  sa.sa_flags = SA_RESTART;
  if (sigaction(SIGCHLD, &sa, NULL) == -1) {
    perror("sigaction");
    exit(1);
  }
  
  printf("servidor: aguardando conexoes...\n");
  
  // Loop de aceitacao principal
  while(1) {
    sin_size = sizeof their_addr;
    new_fd = accept(sockfd, (struct sockaddr *)&their_addr, &sin_size);
    if (new_fd == -1) {
      // perror("accept");
      continue;
    }
    
    inet_ntop(their_addr.ss_family,get_in_addr((struct sockaddr *)&their_addr), s, sizeof s);
    printf("servidor: conexao obtida de %s\n", s);
    
    // Processo filho
    if (!fork()) { 			  

//.........这里部分代码省略.........
开发者ID:fabiothiroki,项目名称:mc823,代码行数:101,代码来源:server.c

示例9: main

int
main(int argc, char **argv)
#endif	/* WIN32 */
{
#ifdef	WIN32
	struct arg_param *p = (struct arg_param *)pv;
	int      		argc;
	char			**argv;
	SERVICE_STATUS          ss;
#endif	/* WIN32 */
	char *name = NULL;
	struct tpp_config conf;
	int rpp_fd;
	char *pc;
	int numthreads;
	char lockfile[MAXPATHLEN + 1];
	char path_log[MAXPATHLEN + 1];
	char svr_home[MAXPATHLEN + 1];
	char *log_file = 0;
	char *host;
	int port;
	char *routers = NULL;
	int c, i, rc;
	extern char *optarg;
	int	are_primary;
	int	num_var_env;
#ifndef WIN32
	struct sigaction act;
	struct sigaction oact;
#endif

#ifndef WIN32
	/*the real deal or just pbs_version and exit*/

	execution_mode(argc, argv);
#endif

	/* As a security measure and to make sure all file descriptors	*/
	/* are available to us,  close all above stderr			*/
#ifdef WIN32
	_fcloseall();
#else
	i = sysconf(_SC_OPEN_MAX);
	while (--i > 2)
		(void)close(i); /* close any file desc left open by parent */
#endif

	/* If we are not run with real and effective uid of 0, forget it */
#ifdef WIN32
	argc = p->argc;
	argv = p->argv;

	ZeroMemory(&ss, sizeof(ss));
	ss.dwCheckPoint = 0;
	ss.dwServiceType = SERVICE_WIN32_OWN_PROCESS;
	ss.dwCurrentState = g_dwCurrentState;
	ss.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
	ss.dwWaitHint = 6000;

	if (g_ssHandle != 0)
		SetServiceStatus(g_ssHandle, &ss);

	if (!isAdminPrivilege(getlogin())) {
		fprintf(stderr, "%s: Must be run by root\n", argv[0]);
		return (2);
	}

#else
	if ((getuid() != 0) || (geteuid() != 0)) {
		fprintf(stderr, "%s: Must be run by root\n", argv[0]);
		return (2);
	}
#endif	/* WIN32 */

	/* set standard umask */
#ifndef WIN32
	umask(022);
#endif

	/* load the pbs conf file */
	if (pbs_loadconf(0) == 0) {
		fprintf(stderr, "%s: Configuration error\n", argv[0]);
		return (1);
	}

	umask(022);

#ifdef	WIN32
	save_env();
#endif
	/* The following is code to reduce security risks                */
	/* start out with standard umask, system resource limit infinite */
	if ((num_var_env = setup_env(pbs_conf.pbs_environment)) == -1) {
#ifdef	WIN32
		g_dwCurrentState = SERVICE_STOPPED;
		ss.dwCurrentState = g_dwCurrentState;
		ss.dwWin32ExitCode = ERROR_INVALID_ENVIRONMENT;
		if (g_ssHandle != 0) SetServiceStatus(g_ssHandle, &ss);
		return (1);
#else
//.........这里部分代码省略.........
开发者ID:A9-William,项目名称:pbspro,代码行数:101,代码来源:pbs_comm.c

示例10: trap_init

void
trap_init(void)
{
  uint8_t digest[20];
  struct sigaction sa, old;
  char path[256];
  int r;
  memset(digest, 0, sizeof(digest));

  r = readlink("/proc/self/exe", self, sizeof(self) - 1);
  if(r == -1)
    self[0] = 0;
  else
    self[r] = 0;

  snprintf(line1, sizeof(line1),
	   "PRG: Showtime (%s) "
	   "[%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"
	   "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x] "
	   "EXE: %s, CWD: %s ", htsversion_full,
	   digest[0],
	   digest[1],
	   digest[2],
	   digest[3],
	   digest[4],
	   digest[5],
	   digest[6],
	   digest[7],
	   digest[8],
	   digest[9],
	   digest[10],
	   digest[11],
	   digest[12],
	   digest[13],
	   digest[14],
	   digest[15],
	   digest[16],
	   digest[17],
	   digest[18],
	   digest[19],
	   self, getcwd(path, sizeof(path)));

  dl_iterate_phdr(callback, NULL);
  

  memset(&sa, 0, sizeof(sa));

  sigset_t m;
  sigemptyset(&m);
  sigaddset(&m, SIGSEGV);
  sigaddset(&m, SIGBUS);
  sigaddset(&m, SIGILL);
  sigaddset(&m, SIGABRT);
  sigaddset(&m, SIGFPE);

  sa.sa_sigaction = traphandler;
  sa.sa_flags = SA_SIGINFO | SA_RESETHAND;
  sigaction(SIGSEGV, &sa, &old);
  sigaction(SIGBUS,  &sa, &old);
  sigaction(SIGILL,  &sa, &old);
  sigaction(SIGABRT, &sa, &old);
  sigaction(SIGFPE,  &sa, &old);

  sigprocmask(SIG_UNBLOCK, &m, NULL);
}
开发者ID:CrashSerious,项目名称:showtime,代码行数:65,代码来源:trap_linux.c

示例11: action_synced_wait


//.........这里部分代码省略.........

    svc_read_output(op->opaque->stdout_fd, op, FALSE);
    svc_read_output(op->opaque->stderr_fd, op, TRUE);

    close(op->opaque->stdout_fd);
    close(op->opaque->stderr_fd);

#ifdef HAVE_SYS_SIGNALFD_H
    close(sfd);
#endif
}

/* For an asynchronous 'op', returns FALSE if 'op' should be free'd by the caller */
/* For a synchronous 'op', returns FALSE if 'op' fails */
gboolean
services_os_action_execute(svc_action_t * op, gboolean synchronous)
{
    int stdout_fd[2];
    int stderr_fd[2];
    struct stat st;
    sigset_t *pmask;

#ifdef HAVE_SYS_SIGNALFD_H
    sigset_t mask;
    sigset_t old_mask;
#define sigchld_cleanup() do {                                                \
    if (sigismember(&old_mask, SIGCHLD) == 0) {                               \
        if (sigprocmask(SIG_UNBLOCK, &mask, NULL) < 0) {                      \
            crm_perror(LOG_ERR, "sigprocmask() failed to unblock sigchld");   \
        }                                                                     \
    }                                                                         \
} while (0)
#else
    struct sigaction sa;
    struct sigaction old_sa;
#define sigchld_cleanup() do {                                                \
    if (sigaction(SIGCHLD, &old_sa, NULL) < 0) {                              \
        crm_perror(LOG_ERR, "sigaction() failed to remove sigchld handler");  \
    }                                                                         \
    close(sigchld_pipe[0]);                                                   \
    close(sigchld_pipe[1]);                                                   \
    sigchld_pipe[0] = sigchld_pipe[1] = -1;                                   \
} while(0)
#endif

    /* Fail fast */
    if(stat(op->opaque->exec, &st) != 0) {
        int rc = errno;
        crm_warn("Cannot execute '%s': %s (%d)", op->opaque->exec, pcmk_strerror(rc), rc);
        services_handle_exec_error(op, rc);
        if (!synchronous) {
            return operation_finalize(op);
        }
        return FALSE;
    }

    if (pipe(stdout_fd) < 0) {
        int rc = errno;

        crm_err("pipe(stdout_fd) failed. '%s': %s (%d)", op->opaque->exec, pcmk_strerror(rc), rc);

        services_handle_exec_error(op, rc);
        if (!synchronous) {
            return operation_finalize(op);
        }
        return FALSE;
开发者ID:yuusuke,项目名称:pacemaker,代码行数:67,代码来源:services_linux.c

示例12: main

int main(int argc, char *argv[])
{
	char *conf_filename;
	int result;
	int sock;
	int wait_count;
	pthread_t schedule_tid;
	struct sigaction act;
	ScheduleEntry scheduleEntries[SCHEDULE_ENTRIES_MAX_COUNT];
	ScheduleArray scheduleArray;
	char pidFilename[MAX_PATH_SIZE];
	bool stop;

	if (argc < 2)
	{
		usage(argv[0]);
		return 1;
	}

	g_current_time = time(NULL);
	g_up_time = g_current_time;

	log_init2();
	trunk_shared_init();

	conf_filename = argv[1];
	if ((result=get_base_path_from_conf_file(conf_filename,
		g_fdfs_base_path, sizeof(g_fdfs_base_path))) != 0)
	{
		log_destroy();
		return result;
	}

	snprintf(pidFilename, sizeof(pidFilename),
		"%s/data/fdfs_storaged.pid", g_fdfs_base_path);
	if ((result=process_action(pidFilename, argv[2], &stop)) != 0)
	{
		if (result == EINVAL)
		{
			usage(argv[0]);
		}
		log_destroy();
		return result;
	}
	if (stop)
	{
		log_destroy();
		return 0;
	}

#if defined(DEBUG_FLAG) && defined(OS_LINUX)
	if (getExeAbsoluteFilename(argv[0], g_exe_name, \
		sizeof(g_exe_name)) == NULL)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return errno != 0 ? errno : ENOENT;
	}
#endif

	memset(g_bind_addr, 0, sizeof(g_bind_addr));
	if ((result=storage_func_init(conf_filename, \
			g_bind_addr, sizeof(g_bind_addr))) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}

	sock = socketServer(g_bind_addr, g_server_port, &result);
	if (sock < 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}

	if ((result=tcpsetserveropt(sock, g_fdfs_network_timeout)) != 0)
	{
		logCrit("exit abnormally!\n");
		log_destroy();
		return result;
	}

	daemon_init(false);
	umask(0);
	if ((result=write_to_pid_file(pidFilename)) != 0)
	{
		log_destroy();
		return result;
	}

	if ((result=storage_sync_init()) != 0)
	{
		logCrit("file: "__FILE__", line: %d, " \
			"storage_sync_init fail, program exit!", __LINE__);
		g_continue_flag = false;
		return result;
	}

//.........这里部分代码省略.........
开发者ID:netroby,项目名称:fastdfs,代码行数:101,代码来源:fdfs_storaged.c

示例13: main

int main()
{
    int p,i;
    int pid,statval;
    char snumproc[5],soml[12],stcpu[5],stes[5];

    struct itimerval itimer;
    struct itimerval otimer;
    struct sigaction act;

    // Obtener los ciclos por tiempo
    sprintf(soml,"%d",(int) get_one_millisec_loop());
    printf("%s\n",soml);

    // Crear semáforo para asegurarse que solo 1 proceso pueda ejecutar handler
    // non_reentrant=semget((key_t)5234, 1, 0666 | IPC_CREAT);
    // set_semvalue(1,non_reentrant);

    // Crear pipe para que el scheduller sepa cual proceso terminó E/S
    unlink("fifo0");
    mkfifo("fifo0",0777);
    fp=fopen("fifo0","r+");

    // Pedir los datos de entrada al usuario
    for(p=0;p<MAXPROC;p++)
    {
         printf("Proceso %d\n",p);
         printf("   Tiempo de llegada ....................... : ");
         scanf("%d",&proceso[p].tinicio);
         printf("   Tiempo de cpu ........................... : ");
         scanf("%d",&proceso[p].tcpu);
         printf("   Tiempo de entrada y salida .............. : ");
         scanf("%d",&proceso[p].tes);
         printf("   Prioridad (usar solo para fixed priority) : ");
         scanf("%d",&proceso[p].prioridad);

         tiempo_total+=proceso[p].tcpu;
         proceso[p].trestante=proceso[p].tcpu;
         proceso[p].estado=NUEVO;
    }

    // Crear los procesos
    for(p=0;p<MAXPROC;p++)
    {
        proceso[p].pid=fork();
        if(proceso[p].pid==0)
        {
            kill(getpid(),SIGSTOP); //SIGSTOP:pause   SIGCONT:continue process
            sprintf(snumproc,"%d",p);
            sprintf(stcpu,"%d",proceso[p].tcpu);
            sprintf(stes,"%d",proceso[p].tes);
            execlp("./proceso","proceso",snumproc,soml,stcpu,stes,NULL);
        }
    }

    printf("Proceso %d\n",getpid());

    // Establece el handler para manejar las señales

    act.sa_handler=handler;
    sigaddset(&act.sa_mask,SIGALRM);
    sigaddset(&act.sa_mask,SIGUSR1);
    sigaddset(&act.sa_mask,SIGUSR2);
    act.sa_flags=SA_RESTART;
    sigaction(SIGALRM,&act,0);//signal inicializa new process

    act.sa_handler=handler;
    sigaddset(&act.sa_mask,SIGALRM);
    sigaddset(&act.sa_mask,SIGUSR1);
    sigaddset(&act.sa_mask,SIGUSR2);
    act.sa_flags=SA_RESTART;
    sigaction(SIGUSR1,&act,0); //signal solicita entrada y salida

    act.sa_handler=handler;
    sigaddset(&act.sa_mask,SIGALRM);
    sigaddset(&act.sa_mask,SIGUSR1);
    sigaddset(&act.sa_mask,SIGUSR2);
    act.sa_flags=SA_RESTART;
    sigaction(SIGUSR2,&act,0); //signal termina entrada y salida


    // Inicializa variables
    listos.ent=0;
    listos.sal=0;
    bloqueados.ent=0;
    bloqueados.sal=0;
    proceso_en_ejecucion=NINGUNO;

    // Inicia el timer
    itimer.it_interval.tv_sec=1;//quantum =1seg
    itimer.it_interval.tv_usec=0;//quantum +=0micros
    itimer.it_value.tv_sec=1;
    itimer.it_value.tv_usec=0;

    if(setitimer(ITIMER_REAL,&itimer,&otimer)<0)
         perror("Error en el settimer");


    // Aquí vamos a esperar a los procesos
    for(p=0;p<MAXPROC;p++)
//.........这里部分代码省略.........
开发者ID:jpramper,项目名称:operativos,代码行数:101,代码来源:virtual_processor.c

示例14: ngx_event_process_init

static ngx_int_t
ngx_event_process_init(ngx_cycle_t *cycle)
{
    ngx_uint_t           m, i;
    ngx_event_t         *rev, *wev;
    ngx_listening_t     *ls;
    ngx_connection_t    *c, *next, *old;
    ngx_core_conf_t     *ccf;
    ngx_event_conf_t    *ecf;
    ngx_event_module_t  *module;

    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);
    ecf = ngx_event_get_conf(cycle->conf_ctx, ngx_event_core_module);

    if (ccf->master && ccf->worker_processes > 1 && ecf->accept_mutex) {
        ngx_use_accept_mutex = 1;
        ngx_accept_mutex_held = 0;
        ngx_accept_mutex_delay = ecf->accept_mutex_delay;

    } else {
        ngx_use_accept_mutex = 0;
    }

#if (NGX_WIN32)

    /*
     * disable accept mutex on win32 as it may cause deadlock if
     * grabbed by a process which can't accept connections
     */

    ngx_use_accept_mutex = 0;

#endif

    ngx_queue_init(&ngx_posted_accept_events);
    ngx_queue_init(&ngx_posted_events);

    if (ngx_event_timer_init(cycle->log) == NGX_ERROR) {
        return NGX_ERROR;
    }

    for (m = 0; cycle->modules[m]; m++) {
        if (cycle->modules[m]->type != NGX_EVENT_MODULE) {
            continue;
        }

        if (cycle->modules[m]->ctx_index != ecf->use) {
            continue;
        }

        module = cycle->modules[m]->ctx;

        if (module->actions.init(cycle, ngx_timer_resolution) != NGX_OK) {
            /* fatal */
            exit(2);
        }

        break;
    }

#if !(NGX_WIN32)

    if (ngx_timer_resolution && !(ngx_event_flags & NGX_USE_TIMER_EVENT)) {
        struct sigaction  sa;
        struct itimerval  itv;

        ngx_memzero(&sa, sizeof(struct sigaction));
        sa.sa_handler = ngx_timer_signal_handler;
        sigemptyset(&sa.sa_mask);

        if (sigaction(SIGALRM, &sa, NULL) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "sigaction(SIGALRM) failed");
            return NGX_ERROR;
        }

        itv.it_interval.tv_sec = ngx_timer_resolution / 1000;
        itv.it_interval.tv_usec = (ngx_timer_resolution % 1000) * 1000;
        itv.it_value.tv_sec = ngx_timer_resolution / 1000;
        itv.it_value.tv_usec = (ngx_timer_resolution % 1000 ) * 1000;

        if (setitimer(ITIMER_REAL, &itv, NULL) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "setitimer() failed");
        }
    }

    if (ngx_event_flags & NGX_USE_FD_EVENT) {
        struct rlimit  rlmt;

        if (getrlimit(RLIMIT_NOFILE, &rlmt) == -1) {
            ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                          "getrlimit(RLIMIT_NOFILE) failed");
            return NGX_ERROR;
        }

        cycle->files_n = (ngx_uint_t) rlmt.rlim_cur;

        cycle->files = ngx_calloc(sizeof(ngx_connection_t *) * cycle->files_n,
                                  cycle->log);
//.........这里部分代码省略.........
开发者ID:ByteInternet,项目名称:nginx,代码行数:101,代码来源:ngx_event.c

示例15: main

int
main(int argc, char **argv)
{
  struct sigaction sa;
  struct netconfig *nconf;
  void *nc_handle;
  in_port_t svcport;
  int ch, i, s;
  char *endptr, **hosts_bak;
  int have_v6 = 1;
  int maxrec = RPC_MAXDATASIZE;
  int attempt_cnt, port_len, port_pos, ret;
  char **port_list;

  while ((ch = getopt(argc, argv, "dh:p:")) != -1)
    switch (ch) {
    case 'd':
      debug = 1;
      break;
    case 'h':
      ++nhosts;
      hosts_bak = hosts;
      hosts_bak = realloc(hosts, nhosts * sizeof(char *));
      if (hosts_bak == NULL) {
	      if (hosts != NULL) {
		      for (i = 0; i < nhosts; i++) 
			      free(hosts[i]);
		      free(hosts);
		      out_of_mem();
	      }
      }
      hosts = hosts_bak;
      hosts[nhosts - 1] = strdup(optarg);
      if (hosts[nhosts - 1] == NULL) {
	      for (i = 0; i < (nhosts - 1); i++) 
		      free(hosts[i]);
	      free(hosts);
	      out_of_mem();
      }
      break;
    case 'p':
      endptr = NULL;
      svcport = (in_port_t)strtoul(optarg, &endptr, 10);
      if (endptr == NULL || *endptr != '\0' || svcport == 0 || 
          svcport >= IPPORT_MAX)
	usage();
      
      svcport_str = strdup(optarg);
      break;
    default:
      usage();
    }
  argc -= optind;
  argv += optind;

  (void)rpcb_unset(SM_PROG, SM_VERS, NULL);

  /*
   * Check if IPv6 support is present.
   */
  s = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
  if (s < 0)
      have_v6 = 0;
  else 
      close(s);

  rpc_control(RPC_SVC_CONNMAXREC_SET, &maxrec);

  /*
   * If no hosts were specified, add a wildcard entry to bind to
   * INADDR_ANY. Otherwise make sure 127.0.0.1 and ::1 are added to the
   * list.
   */
  if (nhosts == 0) {
	  hosts = malloc(sizeof(char**));
	  if (hosts == NULL)
		  out_of_mem();

	  hosts[0] = "*";
	  nhosts = 1;
  } else {
	  hosts_bak = hosts;
	  if (have_v6) {
		  hosts_bak = realloc(hosts, (nhosts + 2) *
		      sizeof(char *));
		  if (hosts_bak == NULL) {
			  for (i = 0; i < nhosts; i++)
				  free(hosts[i]);
			  free(hosts);
			  out_of_mem();
		  } else
			  hosts = hosts_bak;

		  nhosts += 2;
		  hosts[nhosts - 2] = "::1";
	  } else {
		  hosts_bak = realloc(hosts, (nhosts + 1) * sizeof(char *));
		  if (hosts_bak == NULL) {
			  for (i = 0; i < nhosts; i++)
				  free(hosts[i]);
//.........这里部分代码省略.........
开发者ID:JabirTech,项目名称:Source,代码行数:101,代码来源:statd.c


注:本文中的sigaction函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。