• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ setitimer函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: 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; ngx_modules[m]; m++) {
        if (ngx_modules[m]->type != NGX_EVENT_MODULE) {
            continue;
        }

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

        module = ngx_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:ohmori7,项目名称:nginx,代码行数:101,代码来源:ngx_event.c


示例2: ARMul_DoProg

ARMword
ARMul_DoProg (ARMul_State * state)
{
	ARMword pc = 0;

	/*
	 * 2007-01-24 removed the term-io functions by Anthony Lee,
	 * moved to "device/uart/skyeye_uart_stdio.c".
	 */

//teawater add DBCT_TEST_SPEED 2005.10.04---------------------------------------
#ifdef DBCT_TEST_SPEED
	{
		if (!dbct_test_speed_state) {
			//init timer
			struct itimerval	value;
			struct sigaction	act;

			dbct_test_speed_state = state;
			state->instr_count = 0;
			act.sa_handler = dbct_test_speed_sig;
			act.sa_flags = SA_RESTART;
			//cygwin don't support ITIMER_VIRTUAL or ITIMER_PROF
#ifndef __CYGWIN__
			if (sigaction(SIGVTALRM, &act, NULL) == -1) {
#else
			if (sigaction(SIGALRM, &act, NULL) == -1) {
#endif	//__CYGWIN__
				fprintf(stderr, "init timer error.\n");
				skyeye_exit(-1);
			}
			if (skyeye_config.dbct_test_speed_sec) {
				value.it_value.tv_sec = skyeye_config.dbct_test_speed_sec;
			}
			else {
				value.it_value.tv_sec = DBCT_TEST_SPEED_SEC;
			}
			printf("dbct_test_speed_sec = %ld\n", value.it_value.tv_sec);
			value.it_value.tv_usec = 0;
			value.it_interval.tv_sec = 0; 
			value.it_interval.tv_usec = 0;
#ifndef __CYGWIN__
			if (setitimer(ITIMER_VIRTUAL, &value, NULL) == -1) {
#else
			if (setitimer(ITIMER_REAL, &value, NULL) == -1) {
#endif	//__CYGWIN__
				fprintf(stderr, "init timer error.\n");
				skyeye_exit(-1);
			}
		}
	}
#endif	//DBCT_TEST_SPEED
//AJ2D--------------------------------------------------------------------------
	state->Emulate = RUN;
	while (state->Emulate != STOP) {
		state->Emulate = RUN;

		/*ywc 2005-03-31 */
		if (state->prog32Sig && ARMul_MODE32BIT) {
#ifdef DBCT
			if (skyeye_config.no_dbct) {
				pc = ARMul_Emulate32 (state);
			}
			else {
				pc = ARMul_Emulate32_dbct (state);
			}
#else
			pc = ARMul_Emulate32 (state);
#endif
		}

		else {
			pc = ARMul_Emulate26 (state);
		}
		//chy 2006-02-22, should test debugmode first
		//chy 2006-04-14, put below codes in ARMul_Emulate
#if 0
		if(debugmode)
		  if(remote_interrupt())
			state->Emulate = STOP;
#endif
	}

	/*
	 * 2007-01-24 removed the term-io functions by Anthony Lee,
	 * moved to "device/uart/skyeye_uart_stdio.c".
	 */

	return (pc);
}

/***************************************************************************\
* Emulate the execution of one instruction.  Start the correct emulator     *
* (Emulate26 for a 26 bit ARM and Emulate32 for a 32 bit ARM), return the   *
* address of the instruction that is executed.                              *
\***************************************************************************/

ARMword
ARMul_DoInstr (ARMul_State * state)
{
//.........这里部分代码省略.........
开发者ID:aguirrem,项目名称:skyeye,代码行数:101,代码来源:arminit.c


示例3: ngx_master_process_cycle

void
ngx_master_process_cycle(ngx_cycle_t *cycle)
{
    char              *title;
    u_char            *p;
    size_t             size;
    ngx_int_t          i;
    ngx_uint_t         n, sigio;
    sigset_t           set;
    struct itimerval   itv;
    ngx_uint_t         live;
    ngx_msec_t         delay;
    ngx_listening_t   *ls;
    ngx_core_conf_t   *ccf;

    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);
    sigaddset(&set, SIGALRM);
    sigaddset(&set, SIGIO);
    sigaddset(&set, SIGINT);
    sigaddset(&set, ngx_signal_value(NGX_RECONFIGURE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_REOPEN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_NOACCEPT_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_TERMINATE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_CHANGEBIN_SIGNAL));

    if (sigprocmask(SIG_BLOCK, &set, NULL) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "sigprocmask() failed");
    }

    sigemptyset(&set);


    size = sizeof(master_process);

    for (i = 0; i < ngx_argc; i++) {
        size += ngx_strlen(ngx_argv[i]) + 1;
    }

    title = ngx_pnalloc(cycle->pool, size);
    if (title == NULL) {
        /* fatal */
        exit(2);
    }

    p = ngx_cpymem(title, master_process, sizeof(master_process) - 1);
    for (i = 0; i < ngx_argc; i++) {
        *p++ = ' ';
        p = ngx_cpystrn(p, (u_char *) ngx_argv[i], size);
    }

    ngx_setproctitle(title);


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

    ngx_start_worker_processes(cycle, ccf->worker_processes,
                               NGX_PROCESS_RESPAWN);
    ngx_start_cache_manager_processes(cycle, 0);
    
    ngx_start_session_manager_processes(cycle, 0);
    
    ngx_start_ip_blacklist_manager_processes(cycle, 0);

    ngx_new_binary = 0;
    delay = 0;
    sigio = 0;
    live = 1;

    for ( ;; ) {
        if (delay) {
            if (ngx_sigalrm) {
                sigio = 0;
                delay *= 2;
                ngx_sigalrm = 0;
            }

            ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                           "termination cycle: %d", delay);

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

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

        ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "sigsuspend");

        sigsuspend(&set);

        ngx_time_update();

        ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
//.........这里部分代码省略.........
开发者ID:0x08e,项目名称:SENginx,代码行数:101,代码来源:ngx_process_cycle.c


示例4: ngx_event_process_init

// ngx_event_core_module模块的init_process()回调函数。
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

#if (NGX_THREADS)
    ngx_posted_events_mutex = ngx_mutex_init(cycle->log, 0);
    if (ngx_posted_events_mutex == NULL) {
        return NGX_ERROR;
    }
#endif

    // 调用定时器初始化函数。
    if (ngx_event_timer_init(cycle->log) == NGX_ERROR) {
        return NGX_ERROR;
    }


    // 调用被选用事件模型的初始化函数。
    for (m = 0; ngx_modules[m]; m++) {
        if (ngx_modules[m]->type != NGX_EVENT_MODULE) {
            continue;
        }

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

        module = ngx_modules[m]->ctx;

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

        break;
    }

#if !(NGX_WIN32)
    // 如果配置文件里设置timer_resolution字段不为0,修改SIGALRM信号的处理函数为ngx_timer_signal_handler。
    // 并设置以timer_resolution为间隔定时向当前进程发送SIGALRM信号。
    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) {
    // epoll事件模型不会进入这个分支。
        struct rlimit  rlmt;

//.........这里部分代码省略.........
开发者ID:lgqhaoyue,项目名称:nginx-1.6.2-comment,代码行数:101,代码来源:ngx_event.c


示例5: setup

void setup(int icmp_sock)
{
	int hold;
	struct timeval tv;

	if ((options & F_FLOOD) && !(options & F_INTERVAL))
		interval = 0;

	if (uid && interval < MINUSERINTERVAL) {
		fprintf(stderr, "ping: cannot flood; minimal interval, allowed for user, is %dms\n", MINUSERINTERVAL);
		exit(2);
	}

	if (interval >= INT_MAX/preload) {
		fprintf(stderr, "ping: illegal preload and/or interval\n");
		exit(2);
	}

	hold = 1;
	if (options & F_SO_DEBUG)
		setsockopt(icmp_sock, SOL_SOCKET, SO_DEBUG, (char *)&hold, sizeof(hold));
	if (options & F_SO_DONTROUTE)
		setsockopt(icmp_sock, SOL_SOCKET, SO_DONTROUTE, (char *)&hold, sizeof(hold));

#ifdef SO_TIMESTAMP
	if (!(options&F_LATENCY)) {
		int on = 1;
		if (setsockopt(icmp_sock, SOL_SOCKET, SO_TIMESTAMP, &on, sizeof(on)))
			fprintf(stderr, "Warning: no SO_TIMESTAMP support, falling back to SIOCGSTAMP\n");
	}
#endif
	if (options & F_MARK) {
		if (setsockopt(icmp_sock, SOL_SOCKET, SO_MARK,
				&mark, sizeof(mark)) == -1) {
			/* we probably dont wanna exit since old kernels
			 * dont support mark ..
			*/
			fprintf(stderr, "Warning: Failed to set mark %d\n", mark);
		}
	}

	/* Set some SNDTIMEO to prevent blocking forever
	 * on sends, when device is too slow or stalls. Just put limit
	 * of one second, or "interval", if it is less.
	 */
	tv.tv_sec = 1;
	tv.tv_usec = 0;
	if (interval < 1000) {
		tv.tv_sec = 0;
		tv.tv_usec = 1000 * SCHINT(interval);
	}
	setsockopt(icmp_sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&tv, sizeof(tv));

	/* Set RCVTIMEO to "interval". Note, it is just an optimization
	 * allowing to avoid redundant poll(). */
	tv.tv_sec = SCHINT(interval)/1000;
	tv.tv_usec = 1000*(SCHINT(interval)%1000);
	if (setsockopt(icmp_sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&tv, sizeof(tv)))
		options |= F_FLOOD_POLL;

	if (!(options & F_PINGFILLED)) {
		int i;
		u_char *p = outpack+8;

		/* Do not forget about case of small datalen,
		 * fill timestamp area too!
		 */
		for (i = 0; i < datalen; ++i)
			*p++ = i;
	}

	ident = htons(getpid() & 0xFFFF);

	set_signal(SIGINT, sigexit);
	set_signal(SIGALRM, sigexit);
	set_signal(SIGQUIT, sigstatus);

	gettimeofday(&start_time, NULL);

	if (deadline) {
		struct itimerval it;

		it.it_interval.tv_sec = 0;
		it.it_interval.tv_usec = 0;
		it.it_value.tv_sec = deadline;
		it.it_value.tv_usec = 0;
		setitimer(ITIMER_REAL, &it, NULL);
	}

	if (isatty(STDOUT_FILENO)) {
		struct winsize w;

		if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &w) != -1) {
			if (w.ws_col > 0)
				screen_width = w.ws_col;
		}
	}
}
开发者ID:ystk,项目名称:debian-iputils,代码行数:98,代码来源:ping_common.c


示例6: net_write

/*
 *  Do a timed write() of an entire buffer.
 *  Returns
 *
 *	0	=> entire buffer written without error
 *	1	=> write() timed out
 *	-1	=> write() error
 */
int
net_write(int fd, void *buf, size_t buf_size, unsigned timeout)
{
	static char n[] = "net_write";

	int nwrite;
	unsigned char *b, *b_end;
	struct sigaction a;
	struct itimerval t;
	int e;

	b = buf;
	b_end = buf + buf_size;

	/*
	 *  Set the timeout alarm handler.
	 */
	memset(&a, 0, sizeof a);

	alarm_caught = 0;
	a.sa_handler = catch_SIGALRM;
	a.sa_flags = 0;
	sigemptyset(&a.sa_mask);
	t.it_interval.tv_sec = 0;
	t.it_interval.tv_usec = 0;
	t.it_value.tv_sec = timeout;
	t.it_value.tv_usec = 0;
again:
	/*
	 *  Set the ALRM handler.
	 */
	if (sigaction(SIGALRM, &a, (struct sigaction *)0))
		panic3(n, "sigaction(ALRM) failed", strerror(errno));
	/*
	 *  Set the timer
	 */
	if (setitimer(ITIMER_REAL, &t, (struct itimerval *)0))
		panic3(n, "write_buf: setitimer(REAL) failed", strerror(errno));
	nwrite = write(fd, (void *)b, b_end - b);
	e = errno;

	/*
	 *  Disable timer.
	 *
	 *  Note:
	 *	Does setitimer(t.it_interval.tv_sec == 0) above imply
	 *	timer never refires?
	 */
	t.it_value.tv_sec = 0;
	t.it_value.tv_usec = 0;
	if (setitimer(ITIMER_REAL, &t, (struct itimerval *)0))
		panic3(n, "setitimer(REAL, 0) failed", strerror(errno));

	if (nwrite < 0) {
		char tbuf[20];

		if (e != EINTR && e != EAGAIN) {
			error3(n, "write() failed", strerror(errno));
			errno = e;
			return -1;
		}
		if (!alarm_caught)
			goto again;

		alarm_caught = 0;
		snprintf(tbuf, sizeof tbuf, "timed out after %d secs", timeout);
		error3(n, "alarm caught", tbuf);
		return 1;
	}
	b += nwrite;
	if (b < b_end)
		goto again;
	return 0;
}
开发者ID:jmscott,项目名称:blobio,代码行数:82,代码来源:net.c


示例7: main

int main(int argc, char **argv)
{
	int sd, rc, n, tmp;
	char msg[MAX_MSG];
	int nfds;
	int send_timestamp = 0;
	int recv_started = 0;
	struct pollfd *pfds;
	struct alsa_dev *dev;
	CELTEncoder *enc_state;
	CELTDecoder *dec_state;
	CELTMode *mode;
	struct sched_param param;
	JitterBuffer *jitter;
	SpeexEchoState *echo_state;
	char mac_own[6], mac_remote[6];

	if (argc != 4)
		panic("Usage %s plughw:0,0 <lmac in xx:xx:xx:xx:xx:xx> <rmac>\n", argv[0]);
 
	register_signal(SIGINT, sighandler);

	hack_mac(mac_own, argv[2], strlen(argv[2]));
	hack_mac(mac_remote, argv[3], strlen(argv[3]));
 
	sd = socket(AF_LANA, SOCK_RAW, 0);
	if (sd < 0)
		panic("%s: cannot open socket \n", argv[0]);

	printf("If ready hit key!\n"); //user must do binding
	getchar();

	dev = alsa_open(argv[1], SAMPLING_RATE, CHANNELS, FRAME_SIZE);

	mode = celt_mode_create(SAMPLING_RATE, FRAME_SIZE, NULL);
	enc_state = celt_encoder_create(mode, CHANNELS, NULL);
	dec_state = celt_decoder_create(mode, CHANNELS, NULL);

	param.sched_priority = sched_get_priority_min(SCHED_FIFO);
	if (sched_setscheduler(0, SCHED_FIFO, &param))
		whine("sched_setscheduler error!\n");
   
	/* Setup all file descriptors for poll()ing */
	nfds = alsa_nfds(dev);
	pfds = xmalloc(sizeof(*pfds) * (nfds + 1));

	alsa_getfds(dev, pfds, nfds);

	pfds[nfds].fd = sd;
	pfds[nfds].events = POLLIN;

	/* Setup jitter buffer using decoder */
	jitter = jitter_buffer_init(FRAME_SIZE);
	tmp = FRAME_SIZE;
	jitter_buffer_ctl(jitter, JITTER_BUFFER_SET_MARGIN, &tmp);

	/* Echo canceller with 200 ms tail length */
	echo_state = speex_echo_state_init(FRAME_SIZE, 10 * FRAME_SIZE);
	tmp = SAMPLING_RATE;
	speex_echo_ctl(echo_state, SPEEX_ECHO_SET_SAMPLING_RATE, &tmp);

	register_signal_f(SIGALRM, timer_elapsed, SA_SIGINFO);

	alsa_start(dev);
	printf("ALSA started!\n");

	itimer.it_interval.tv_sec = 0;
	itimer.it_interval.tv_usec = interval;
	itimer.it_value.tv_sec = 0;
	itimer.it_value.tv_usec = interval;
	setitimer(ITIMER_REAL, &itimer, NULL);

	while (!sigint) {
		poll(pfds, nfds + 1, -1);

		/* Received packets */
		if (pfds[nfds].revents & POLLIN) {
			memset(msg, 0, MAX_MSG);
			n = recv(sd, msg, MAX_MSG, 0);
			if (n <= 0)
				goto do_alsa;
			pkts_in++;
			int recv_timestamp;
			memcpy(&recv_timestamp, msg, sizeof(recv_timestamp));
			JitterBufferPacket packet;
			packet.data = msg+4/*+6+6+2*/;
			packet.len = n-4/*-6-6-2*/;
			packet.timestamp = recv_timestamp;
			packet.span = FRAME_SIZE;
			packet.sequence = 0;

			/* Put content of the packet into the jitter buffer,
			   except for the pseudo-header */
			jitter_buffer_put(jitter, &packet);
			recv_started = 1;
		}
do_alsa:
		/* Ready to play a frame (playback) */
		if (alsa_play_ready(dev, pfds, nfds)) {
			short pcm[FRAME_SIZE * CHANNELS] = {0};
//.........这里部分代码省略.........
开发者ID:pharmafirma,项目名称:reconos,代码行数:101,代码来源:voe.c


示例8: do_test


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

  ts.tv_nsec = -1;
  if (mq_timedreceive (q, buf, 2, NULL, &ts) == 0)
    {
      puts ("mq_timedreceive with negative tv_nsec did not fail");
      result = 1;
    }
  else if (errno != EINVAL)
    {
      printf ("mq_timedreceive with negative tv_nsec did not fail with "
	      "EINVAL: %m\n");
      result = 1;
    }

  ts.tv_nsec = 1000000000;
  if (mq_timedreceive (q, buf, 2, NULL, &ts) == 0)
    {
      puts ("mq_timedreceive with tv_nsec >= 1000000000 did not fail");
      result = 1;
    }
  else if (errno != EINVAL)
    {
      printf ("mq_timedreceive with tv_nsec >= 1000000000 did not fail with "
	      "EINVAL: %m\n");
      result = 1;
    }

  struct sigaction sa = { .sa_handler = alrm_handler, .sa_flags = 0 };
  sigemptyset (&sa.sa_mask);
  sigaction (SIGALRM, &sa, NULL);

  struct itimerval it = { .it_value = { .tv_sec = 1 } };
  setitimer (ITIMER_REAL, &it, NULL);

  if (mq_receive (q, buf, 2, NULL) == 0)
    {
      puts ("mq_receive on empty queue did not block");
      result = 1;
    }
  else if (errno != EINTR)
    {
      printf ("mq_receive on empty queue did not fail with EINTR: %m\n");
      result = 1;
    }

  setitimer (ITIMER_REAL, &it, NULL);

  ts.tv_nsec = 0;
  if (mq_timedreceive (q, buf, 2, NULL, &ts) == 0)
    {
      puts ("mq_timedreceive on empty queue did not block");
      result = 1;
    }
  else if (errno != EINTR)
    {
      printf ("mq_timedreceive on empty queue did not fail with EINTR: %m\n");
      result = 1;
    }

  buf[0] = '6';
  buf[1] = '7';
  if (mq_send (q, buf, 2, 3) != 0
      || (buf[0] = '8', mq_send (q, buf, 1, 4) != 0))
    {
      printf ("mq_send failed: %m\n");
开发者ID:Akheon23,项目名称:chromecast-mirrored-source.toolchain,代码行数:67,代码来源:tst-mqueue2.c


示例9: mpx_handler


//.........这里部分代码省略.........
					cur_event->count_estimate +=
						( long long ) ( ( double ) total_cycles *
										cur_event->rate_estimate );
                                        MPXDBG("New estimate = %lld (%lld cycles * %lf rate)\n",
                                               cur_event->count_estimate,total_cycles,
                                               cur_event->rate_estimate);
				} else {
					/* Make sure we ran long enough to get a useful measurement (otherwise
					 * potentially inaccurate rate measurements get averaged in with
					 * the same weight as longer, more accurate ones.)
					 */
					if ( cycles >= MPX_MINCYC ) {
						cur_event->cycles += 1;
					} else {
						cur_event->count -= counts[0];
					}
				}
			} else {
				MPXDBG( "%lx retval = %d, skipping\n", me->tid, retval );
				MPXDBG( "%lx value = %lld cycles = %lld\n\n",
						me->tid, cur_event->count, cur_event->cycles );
			}

			MPXDBG
				( "tid(%lx): value = %lld (%lld) cycles = %lld (%lld) rate = %lf\n\n",
				  me->tid, cur_event->count, cur_event->count_estimate,
				  cur_event->cycles, total_cycles, cur_event->rate_estimate );
			/* Start running the next event; look for the
			 * next one in the list that's marked active.
			 * It's possible that this event is the only
			 * one active; if so, we should restart it,
			 * but only after considerating all the other
			 * possible events.
			 */
			if ( ( retval != PAPI_OK ) ||
				 ( ( retval == PAPI_OK ) && ( cycles >= MPX_MINCYC ) ) ) {
				for ( mev =
					  ( cur_event->next == NULL ) ? head : cur_event->next;
					  mev != cur_event;
					  mev = ( mev->next == NULL ) ? head : mev->next ) {
					/* Found the next one to start */
					if ( mev->active ) {
						me->cur_event = mev;
						break;
					}
				}
			}

			if ( me->cur_event->active ) {
				retval = PAPI_start( me->cur_event->papi_event );
			}
#ifdef MPX_DEBUG_OVERHEAD
			didwork = 1;
#endif
		}
	}
#ifdef ANY_THREAD_GETS_SIGNAL
	else {
		Threadlist *t;
		for ( t = tlist; t != NULL; t = t->next ) {
			if ( ( t->tid == _papi_hwi_thread_id_fn(  ) ) ||
				 ( t->head == NULL ) )
				continue;
			MPXDBG( "forwarding signal to thread %lx\n", t->tid );
			retval = ( *_papi_hwi_thread_kill_fn ) ( t->tid, _papi_os_info.itimer_sig );
			if ( retval != 0 ) {
				MPXDBG( "forwarding signal to thread %lx returned %d\n",
						t->tid, retval );
			}
		}
	}
#endif

#ifdef REGENERATE
	/* Regenerating the signal each time through has the
	 * disadvantage that if any thread ever drops a signal,
	 * the whole time slicing system will stop.  Using
	 * an automatically regenerated signal may have the
	 * disadvantage that a new signal can arrive very
	 * soon after all the threads have finished handling
	 * the last one, so the interval may be too small for
	 * accurate data collection.  However, using the
	 * MIN_CYCLES check above should alleviate this.
	 */
	/* Reset the timer once all threads have responded */
	if ( lastthread ) {
		retval = setitimer( _papi_os_info.itimer_num, &itime, NULL );
		assert( retval == 0 );
#ifdef MPX_DEBUG_TIMER
		MPXDBG( "timer restarted by %lx\n", me->tid );
#endif
	}
#endif

#ifdef MPX_DEBUG_OVERHEAD
	usec = _papi_hwd_get_real_usec(  ) - usec;
	MPXDBG( "handler %#x did %swork in %lld usec\n",
			self, ( didwork ? "" : "no " ), usec );
#endif
}
开发者ID:DanieleDeSensi,项目名称:mammut,代码行数:101,代码来源:sw_multiplex.c


示例10: main


//.........这里部分代码省略.........
			strcpy(o_buf, x);
			if (o_size >= 3) {
				x = "*0";
				if (setting[0] == '*' && setting[1] == '0')
					x = "*1";
			}
			__set_errno(0);
			p = crypt_rn(key, setting, o_buf, o_size);
			if ((ok_n && (!p || strcmp(p, hash))) ||
			    (!ok_n && (!errno || p || strcmp(o_buf, x)))) {
				printf("FAILED (crypt_rn/%d)\n", i);
				return 1;
			}
		}

		__set_errno(0);
		p = crypt_ra(key, setting, &data, &size);
		if ((ok && (!p || strcmp(p, hash))) ||
		    (!ok && (!errno || p || strcmp((char *)data, hash)))) {
			printf("FAILED (crypt_ra/%d)\n", i);
			return 1;
		}
	}

	setting1 = crypt_gensalt(which[0], 12, data, size);
	if (!setting1 || strncmp(setting1, "$2a$12$", 7)) {
		puts("FAILED (crypt_gensalt)\n");
		return 1;
	}

	setting2 = crypt_gensalt_ra(setting1, 12, data, size);
	if (strcmp(setting1, setting2)) {
		puts("FAILED (crypt_gensalt_ra/1)\n");
		return 1;
	}

	(*(char *)data)++;
	setting1 = crypt_gensalt_ra(setting2, 12, data, size);
	if (!strcmp(setting1, setting2)) {
		puts("FAILED (crypt_gensalt_ra/2)\n");
		return 1;
	}

	free(setting1);
	free(setting2);
	free(data);

#if defined(_SC_CLK_TCK) || !defined(CLK_TCK)
	clk_tck = sysconf(_SC_CLK_TCK);
#else
	clk_tck = CLK_TCK;
#endif

	running = 1;
	signal(SIGALRM, handle_timer);

	memset(&it, 0, sizeof(it));
	it.it_value.tv_sec = 5;
	setitimer(ITIMER_REAL, &it, NULL);

	start_real = times(&buf);
	start_virtual = buf.tms_utime + buf.tms_stime;

	count = (char *)run((char *)0) - (char *)0;

	end_real = times(&buf);
	end_virtual = buf.tms_utime + buf.tms_stime;
	if (end_virtual == start_virtual) end_virtual++;

	printf("%.1f c/s real, %.1f c/s virtual\n",
		(float)count * clk_tck / (end_real - start_real),
		(float)count * clk_tck / (end_virtual - start_virtual));

#ifdef TEST_THREADS
	running = 1;
	it.it_value.tv_sec = 60;
	setitimer(ITIMER_REAL, &it, NULL);
	start_real = times(&buf);

	for (i = 0; i < TEST_THREADS; i++)
	if (pthread_create(&t[i], NULL, run, i + (char *)0)) {
		perror("pthread_create");
		return 1;
	}

	for (i = 0; i < TEST_THREADS; i++) {
		if (pthread_join(t[i], &t_retval)) {
			perror("pthread_join");
			continue;
		}
		if (!t_retval) continue;
		count = (char *)t_retval - (char *)0;
		end_real = times(&buf);
		printf("%d: %.1f c/s real\n", i,
			(float)count * clk_tck / (end_real - start_real));
	}
#endif

	return 0;
}
开发者ID:LeifAndersen,项目名称:bcrypt.rkt,代码行数:101,代码来源:wrapper.c


示例11: ftp_master_process_cycle

void ftp_master_process_cycle()
{
    int fd = open("/dev/zero",O_RDWR,0);
    mptr = mmap(0,sizeof(pthread_mutex_t),PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
    close(fd);

    ftp_process_identity = FTP_MASTER_PROCESS;

    pthread_mutexattr_t mattr;
    pthread_mutexattr_init(&mattr);
    pthread_mutexattr_setpshared(&mattr,PTHREAD_PROCESS_SHARED);
    pthread_mutex_init(mptr,&mattr);

	sigset_t set;
	sigemptyset(&set);
	sigaddset(&set,SIGCHLD);
	sigaddset(&set,SIGINT);
	sigaddset(&set,SIGTERM);
	sigaddset(&set,SIGALRM);
	if(sigprocmask(SIG_SETMASK,&set,NULL) == 1){
		err_quit("ftp_master_process_cycle - sigprocmask");
	}

    int i;
    for(i = 0;i < max_connections;i++)
        ftp_respawn_work_process(i);

    close(ftp_listenfd);

    sigemptyset(&set);

    unsigned delay = 0;
	while(1) {
		sigsuspend(&set);
		if(ftp_sigchld) {
            ftp_sigchld = 0;
            int alive = 0 ;
            for(i = 0;i < max_connections;i++) {
                if(ftp_process[i].pid == -1 && !ftp_process[i].exited) {
                    ftp_respawn_work_process(i);
                }
                if(ftp_process[i].pid)  alive = 1;
            }
            if(!alive && (ftp_terminate || ftp_quit))   exit(0);
		}

        if(ftp_terminate) {
            if(delay == 0) {
                delay = 2000;
                struct itimerval t;
                t.it_interval.tv_sec = 0;
                t.it_interval.tv_usec = 0;
                t.it_value.tv_sec = delay / 1000;
                t.it_value.tv_usec = delay % 1000 * 1000;
                setitimer(ITIMER_REAL,&t,NULL);
            }
            ftp_signal_work_process(SIGTERM);
        }

        if(ftp_sigalrm) {
            ftp_signal_work_process(SIGKILL);
        }

	}

}
开发者ID:gzwl,项目名称:FtpServer,代码行数:66,代码来源:ftp_process_cycle.c


示例12: ngx_master_process_cycle

void
ngx_master_process_cycle(ngx_cycle_t *cycle)
{
    char              *title;
    u_char            *p;
    size_t             size;
    ngx_int_t          i;
    ngx_uint_t         n, sigio;
    sigset_t           set;
    struct itimerval   itv;
    ngx_uint_t         live;
    ngx_msec_t         delay;
    ngx_listening_t   *ls;
    ngx_core_conf_t   *ccf;

    //屏蔽一系列信号,防止被打扰
    sigemptyset(&set);
    sigaddset(&set, SIGCHLD);
    sigaddset(&set, SIGALRM);
    sigaddset(&set, SIGIO);
    sigaddset(&set, SIGINT);
    sigaddset(&set, ngx_signal_value(NGX_RECONFIGURE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_REOPEN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_NOACCEPT_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_TERMINATE_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_SHUTDOWN_SIGNAL));
    sigaddset(&set, ngx_signal_value(NGX_CHANGEBIN_SIGNAL));

    if (sigprocmask(SIG_BLOCK, &set, NULL) == -1) {
        ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                      "sigprocmask() failed");
    }

    sigemptyset(&set);


    // master_process 静态数组。参考本页
    size = sizeof(master_process);

    for (i = 0; i < ngx_argc; i++) {
        size += ngx_strlen(ngx_argv[i]) + 1;
    }

    title = ngx_pnalloc(cycle->pool, size);

    p = ngx_cpymem(title, master_process, sizeof(master_process) - 1);
    for (i = 0; i < ngx_argc; i++) {
        *p++ = ' ';
        p = ngx_cpystrn(p, (u_char *) ngx_argv[i], size);
    }

    ngx_setproctitle(title);

    //master进程获取core模块配置,ccf中有要创建多少个worker的设定
    ccf = (ngx_core_conf_t *) ngx_get_conf(cycle->conf_ctx, ngx_core_module);

    //启动worker,这时已经有了worker进程
    // NGX_PROCESS_RESPAWN 表示重新生成子进程
    ngx_start_worker_processes(cycle, ccf->worker_processes,            
                               NGX_PROCESS_RESPAWN);
    ngx_start_cache_manager_processes(cycle, 0);  //创建有关cache的子进程

    ngx_new_binary = 0;
    delay = 0;
    sigio = 0;
    live = 1;

    for ( ;; ) {
        //delay用来等待子进程退出的时间,由于我们接受到SIGINT信号后,我们需要先发送信号给子进程,
        //而子进程的退出需要一定的时间,超时时如果子进程已退出,我们父进程就直接退出,
        //否则发送sigkill信号给子进程(强制退出),然后再退出。  
        if (delay) {
            if (ngx_sigalrm) {
                sigio = 0;
                delay *= 2;
                ngx_sigalrm = 0;
            }

            ngx_log_debug1(NGX_LOG_DEBUG_EVENT, cycle->log, 0,
                           "termination cycle: %d", delay);

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

            //设置定时器
            if (setitimer(ITIMER_REAL, &itv, NULL) == -1) {
                ngx_log_error(NGX_LOG_ALERT, cycle->log, ngx_errno,
                              "setitimer() failed");
            }
        }

        ngx_log_debug0(NGX_LOG_DEBUG_EVENT, cycle->log, 0, "sigsuspend");

        //延时,等待信号
        sigsuspend(&set);  //调用这个将master进程挂起来

        ngx_time_update();

//.........这里部分代码省略.........
开发者ID:liudexin,项目名称:nginx-node,代码行数:101,代码来源:ngx_process_cycle.c


示例13: set_rotation_timer

int
set_rotation_timer()
{
#if 0
    double secs_left = 0.0L;
#endif
    struct itimerval itimer = {};
    struct sigaction sa = {
        .sa_sigaction = handler_alarm,
        .sa_flags = SA_RESTART | SA_SIGINFO,
    };
    sigemptyset(&sa.sa_mask);
    sigaction(SIGALRM, &sa, NULL);

#if 0
    secs_left = get_seconds_left_in_today();
    az_log(LOG_DEBUG, "secs_left = %lf", secs_left);

    itimer.it_interval.tv_sec = secs_left;
#else
    itimer.it_interval.tv_sec = 1;
#endif
    itimer.it_interval.tv_usec = 0;
    itimer.it_value = itimer.it_interval;
    assert(setitimer(ITIMER_REAL, &itimer, 0) == 0);

    return 0;
}

int
do_rotate(sc_aggregator_connection_ref conn)
{
    sc_config_pattern_entry *pe;
    struct tm tm;
    time_t t;
    sc_follow_context* cxt = NULL;
    int not_found;
    az_list *li, *lp;

    time(&t);
    localtime_r(&t, &tm);
    for (lp = g_config_patterns; lp; lp = lp->next) {
        pe = (sc_config_pattern_entry*)lp->object;
        char fn[PATH_MAX], dn[PATH_MAX];

        if (pe->rotate && strchr(pe->path, '%')) {
	    strftime(fn, sizeof(fn), pe->path, &tm);
	} else {
	    strncpy(fn, pe->path, sizeof(fn));
	}

	if (pe->displayName) {
	    if (pe->rotate && strchr(pe->displayName, '%')) {
	        strftime(dn, sizeof(dn), pe->displayName, &tm);
	    } else {
	        strncpy(dn, pe->displayName, sizeof(dn));
	    }
	} else {
	    strcpy(dn, basename(fn));
	}
        az_log(LOG_DEBUG, "fname = [%s] / dispname = [%s]", fn, dn);

        not_found = 1;
        for (li = g_context_list; not_found && li; li = li->next) {
            cxt = li->object;
            if (cxt->filename && strcmp(cxt->filename, fn) == 0) {
		if (strcmp(cxt->displayName, dn) == 0) {
                    // , I'm already following it.
                    not_found = 0;
		} else {
		    // displayName has rotated.
		    sc_follow_context_close(cxt);
		}
                az_log(LOG_DEBUG, "=== already following now.", fn, dn);
                break;
            }
        }

        if (not_found) {
            cxt = sc_follow_context_new(fn, dn, pe->append_timestamp, BUFSIZE, conn);
            g_context_list = az_list_add(g_context_list, cxt);
            az_log(LOG_DEBUG, "added: new follow_context");
        }
    }

#if 0
    for (li = g_controller_list; li; li = li->next) {
        char dn[PATH_MAX];
        sc_controller* contr = li->object;

        if (contr->displayName == NULL) {
            continue;
        }

        if (strchr(contr->displayName, '%')) {
	    strftime(dn, sizeof(dn), contr->displayName, &tm);
        } else {
            strncpy(dn, contr->displayName, sizeof(dn));
        }

//.........这里部分代码省略.........
开发者ID:koura-h,项目名称:compostela,代码行数:101,代码来源:main.c


示例14: xmit_slowpath_or_die


//.........这里部分代码省略.........
	stats[cpu].tv_sec = diff.tv_sec;
	stats[cpu].tv_usec = diff.tv_usec;

	stats[cpu].state |= CPU_STATS_STATE_RES;
}

static void xmit_fastpath_or_die(struct ctx *ctx, int cpu, unsigned long orig_num)
{
	int ifindex = device_ifindex(ctx->device);
	uint8_t *out = NULL;
	unsigned int it = 0;
	unsigned long num = 1, i = 0, size;
	struct ring tx_ring;
	struct frame_map *hdr;
	struct timeval start, end, diff;
	struct packet_dyn *pktd;
	unsigned long long tx_bytes = 0, tx_packets = 0;

	fmemset(&tx_ring, 0, sizeof(tx_ring));

	size = ring_size(ctx->device, ctx->reserve_size);

	set_sock_prio(sock, 512);
	set_packet_loss_discard(sock);

	setup_tx_ring_layout(sock, &tx_ring, size, ctx->jumbo_support);
	create_tx_ring(sock, &tx_ring, ctx->verbose);
	mmap_tx_ring(sock, &tx_ring);
	alloc_tx_ring_frames(sock, &tx_ring);
	bind_tx_ring(sock, &tx_ring, ifindex);

	drop_privileges(ctx->enforce, ctx->uid, ctx->gid);

	if (ctx->kpull)
		interval = ctx->kpull;
	if (ctx->num > 0)
		num = ctx->num;
	if (ctx->num == 0 && orig_num > 0)
		num = 0;

	set_itimer_interval_value(&itimer, 0, interval);
	setitimer(ITIMER_REAL, &itimer, NULL); 

	bug_on(gettimeofday(&start, NULL));

	while (likely(sigint == 0 && num > 0 && plen > 0)) {
		if (!user_may_pull_from_tx(tx_ring.frames[it].iov_base)) {
			sched_yield();
			continue;
		}

		hdr = tx_ring.frames[it].iov_base;
		out = ((uint8_t *) hdr) + TPACKET2_HDRLEN - sizeof(struct sockaddr_ll);

		hdr->tp_h.tp_snaplen = packets[i].len;
		hdr->tp_h.tp_len = packets[i].len;

		pktd = &packet_dyn[i];
		if (pktd->clen + pktd->rlen + pktd->slen) {
			apply_counter(i);
			apply_randomizer(i);
			apply_csum16(i);
		}

		fmemcpy(out, packets[i].payload, packets[i].len);

		tx_bytes += packets[i].len;
		tx_packets++;

		if (!ctx->rand) {
			i++;
			if (i >= plen)
				i = 0;
		} else
			i = rand() % plen;

		kernel_may_pull_from_tx(&hdr->tp_h);

		it++;
		if (it >= tx_ring.layout.tp_frame_nr)
			it = 0;

		if (ctx->num > 0)
			num--;
	}

	bug_on(gettimeofday(&end, NULL));
	timersub(&end, &start, &diff);

	timer_purge();

	destroy_tx_ring(sock, &tx_ring);

	stats[cpu].tx_packets = tx_packets;
	stats[cpu].tx_bytes = tx_bytes;
	stats[cpu].tv_sec = diff.tv_sec;
	stats[cpu].tv_usec = diff.tv_usec;

	stats[cpu].state |= CPU_STATS_STATE_RES;
}
开发者ID:uvt,项目名称:netsniff-ng,代码行数:101,代码来源:trafgen.c


示例15: lock

void t_timekeeper::start_timer(t_timer *t) {
	struct itimerval	itimer;
	long			remain_msec;

	lock();

	// The next interval option is not used
	itimer.it_interval.tv_sec = 0;
	itimer.it_interval.tv_usec = 0;

	// Get duration of the timer to start
	long d = t->get_relative_duration();

	// If no timer is currently running then simply start the timer
	if (timer_list.empty()) {
		timer_list.push_back(t);
		itimer.it_value.tv_sec = d / 1000;
		itimer.it_value.tv_usec = (d % 1000) * 1000;
		setitimer(ITIMER_REAL, &itimer, NULL);

		unlock();
		return;
	}

	// Get remaining duration of current running timer
	getitimer(ITIMER_REAL, &itimer);
	remain_msec = itimer.it_value.tv_sec * 1000 +
		      itimer.it_value.tv_usec / 1000;

	// If the new timer is shorter than the current timer.
	// then the new timer should be run first.
	if (d < remain_msec) {
		// Change running timer to new timer
		itimer.it_value.tv_sec = d / 1000;
		itimer.it_value.tv_usec = (d % 1000) * 1000;
		setitimer(ITIMER_REAL, &itimer, NULL);

		// Calculate the relative duration the timer
		// that was running.
		t_timer *old_timer = timer_list.front();
		old_timer->set_relative_duration(remain_msec - d);

		// Add new timer at the front of the list
		timer_list.push_front(t);

		unlock();
		return;
	}

	// Calculate the relative duration for the new timer
	long new_duration = d - remain_msec;

	// Insert the new timer at the right position in the list.
	list<t_timer *>::iterator i;
	for (i = timer_list.begin(); i != timer_list.end(); i++)
	{
		// skip the first timer
		if (i == timer_list.begin()) continue;

		long dur = (*i)->get_relative_duration();
		if (new_duration < dur) {
			// Adjust relative duration existing timer
			(*i)->set_relative_duration(dur - new_duration);

			// Insert new timer before existing timer
			t->set_relative_duration(new_duration);
			timer_list.insert(i, t);

			unlock();
			return;
		}

		new_duration -= dur;
	}

	// Add the new timer to the end of the list
	t->set_relative_duration(new_duration);
	timer_list.push_back(t);

	unlock();
}
开发者ID:LubosD,项目名称:twinkle,代码行数:81,代码来源:timekeeper.cpp


示例16: net_read

/*
 *  Do a timed read of some bytes on the network.
 *
 *	>= 0	=> read some bytes
 *	-1	=> read() error
 *	-2	=> timeout
 */
ssize_t
net_read(int fd, void *buf, size_t buf_size, unsigned timeout)
{
	static char n[] = "net_read";

	ssize_t nread;
	int e;
	struct sigaction a;
	struct itimerval t;

	/*
	 *  Set the timeout alarm handler.
	 */
	memset(&a, 0, sizeof a);
	alarm_caught = 0;
	a.sa_handler = catch_SIGALRM;
	a.sa_flags = 0;
	sigemptyset(&a.sa_mask);
	t.it_interval.tv_sec = 0;
	t.it_interval.tv_usec = 0;
	t.it_value.tv_sec = timeout;
	t.it_value.tv_usec = 0;
again:
	/*
	 *  Set the alarm handler.
	 */
	if (sigaction(SIGALRM, &a, (struct sigaction *)0))
		panic3(n, "sigaction(ALRM) failed", strerror(errno));
	/*
	 *  Set the interval time.
	 */
	if (setitimer(ITIMER_REAL, &t, (struct itimerval *)0))
		panic3(n, "setitimer(REAL) failed", strerror(errno));

	nread = read(fd, (void *)buf, buf_size);
	e = errno;

	/*
	 *  Disable timer.
	 *
	 *  Note:
	 *	Does setitimer(t.it_interval.tv_sec == 0) above imply
	 *	timer never refires?
	 */
	t.it_value.tv_sec = 0;
	if (setitimer(ITIMER_REAL, &t, (struct itimerval *)0))
		panic3(n, "setitimer(REAL) reset failed", strerror(errno));

	if (nread < 0) {
		char tbuf[27];

		if (e != EINTR && e != EAGAIN) {
			error3(n, "read() failed", strerror(e));
			errno = e;
			return -1;
		}
		if (!alarm_caught)
			goto again;

		alarm_caught = 0;
		snprintf(tbuf, sizeof tbuf, "timed out after %d secs", timeout);
		error3(n, "alarm caught", tbuf);
		return -2;
	}
	return nread;
}
开发者ID:jmscott,项目名称:blobio,代码行数:73,代码来源:net.c


示例17: ne


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ setivalue函数代码示例发布时间:2022-05-30
下一篇:
C++ setintV函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap