本文整理汇总了C++中FD_ZERO函数的典型用法代码示例。如果您正苦于以下问题:C++ FD_ZERO函数的具体用法?C++ FD_ZERO怎么用?C++ FD_ZERO使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了FD_ZERO函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: main
//.........这里部分代码省略.........
printf(" watchtower 'echo $F' /home/user # prints any filenames modified under "
"/home/user\n");
printf("\n");
printf("Available options:\n");
printf(" -h, --help print this message\n");
printf(" -v, --version print program version\n");
printf(" -r, --recursive set program to watch entire subtree\n");
ret = EXIT_SUCCESS;
goto done;
}
if (recursive_flag)
fprintf(stderr, "WARNING: recursive mode is not yet implemented\n");
command = argv[optind++];
path = argv[optind];
memset(&hints, 0, sizeof(struct fileinfo));
hints.fi_type = DT_DIR;
if ((res = getfileinfo(path, &hints, &info)) != 0) {
fprintf(stderr, "getfileinfo: %s\n", gfi_strerror(res));
goto done;
}
infd = inotify_init();
for (p = info; p; p = p->fi_next) {
if (strcmp(p->fi_name, "..") == 0)
continue;
if (strcmp(p->fi_name, ".") == 0)
inwd = inotify_add_watch(infd, p->fi_path, IN_MODIFY);
}
freefileinfo(info);
sigemptyset(&sigmask);
sigaddset(&sigmask, SIGINT);
sigprocmask(SIG_BLOCK, &sigmask, NULL);
sa.sa_flags = 0;
sa.sa_handler = interrupt_handler;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
sigemptyset(&empty_mask);
for (;;) {
FD_ZERO(&fds);
FD_SET(infd, &fds);
pselect(infd + 1, &fds, NULL, NULL, NULL, &empty_mask);
if (got_SIGINT) {
printf("\ncleaning up...\n");
break;
}
len = read(infd, buf, BUFFER_SIZE);
for (iter = buf; iter < buf + len;
iter += sizeof(struct inotify_event) + event->len) {
event = (const struct inotify_event *)iter;
if (event->mask & IN_MODIFY) {
pid = fork();
switch (pid) {
case -1:
fprintf(stderr, "forking failed\n");
break;
case 0:
env[0] = malloc(strlen(event->name) + 3);
sprintf(env[0], "F=%s", event->name);
env[1] = NULL;
execle("/bin/sh", "sh", "-c", command, (char *)NULL, env);
free(env[0]);
ret = EXIT_SUCCESS;
goto done;
default:
fflush(NULL);
if (waitpid(pid, &status, 0) == -1)
fprintf(stderr, "child process failed\n");
break;
}
}
}
}
inotify_rm_watch(infd, inwd);
close(infd);
ret = EXIT_SUCCESS;
done:
return ret;
}
示例2: gwrl_bkd_gather
void gwrl_bkd_gather(gwrl * rl) {
int res = 0;
gwrlevt_flags_t newflags = 0;
fd_set fds[3];
gwrlsrc * src = NULL;
gwrlsrc_file * fsrc = NULL;
gwrlevt * evt = NULL;
gwrlbkd * bkd = rl->backend;
gwrlbkd_select * sbkd = _gwrlbkds(bkd);
//setup timeout for select
struct timeval timeout;
struct timeval * timeoutp = &timeout;
if(bkd->timeout.tv_sec == sec_min && bkd->timeout.tv_nsec == nsec_min) {
timeoutp = NULL;
} else {
gwtm_timespec_to_timeval(&bkd->timeout,&timeout);
}
//if sleep isn't allowed set timeout to 0
if(!timeoutp && flisset(rl->flags,GWRL_NOSLEEP)) {
timeoutp = &timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
#ifdef GWRL_COVERAGE_INTERNAL_ASSERT_VARS
if(asserts_var1 == gwrlbkd_no_sleep_assert_true) {
asserts_var2 = true;
}
#endif
}
//initialize fds
FD_ZERO(&(fds[0]));
FD_ZERO(&(fds[1]));
FD_ZERO(&(fds[2]));
//reset fds
memcpy(&(fds[0]),&(sbkd->src[0]),sizeof(fd_set));
memcpy(&(fds[1]),&(sbkd->src[1]),sizeof(fd_set));
memcpy(&(fds[2]),&(sbkd->src[2]),sizeof(fd_set));
//call select, wrapped in sleeping flags so other threads can wake us
flset(rl->flags,GWRL_SLEEPING);
res = select(sbkd->maxfd+1,&(fds[0]),&(fds[1]),&(fds[2]),timeoutp);
flclr(rl->flags,GWRL_SLEEPING);
if(res == 0) return; //timeout
//break and let the event loop continue or start over.
//if a signal did happen, the event loop may have an
//event that needs processing.
if(res < 0 && (errno == EINTR || errno == EAGAIN)) return;
//bad fd, unforunately select doesn't tell us which
//one it was so we have to search for it.
if(res < 0 && errno == EBADF) {
gwrl_src_file_find_badfd_post_evt(rl);
return;
}
//invalid timeout or invalid number of fds.
if(res < 0 && errno == EINVAL) {
//invalid timeout, break and let process events recalculate timeouts.
if(timeout.tv_sec < 0 || timeout.tv_usec < 0) return;
//nfds parameter to select() is too large, not sure how to handle
fprintf(stderr,"select: file descriptor limit reached. exiting. \n");
exit(1);
}
//valid events are ready
if(res > 0) {
fsrc = _gwrlsrcf(rl->sources[GWRL_SRC_TYPE_FILE]);
while(fsrc) {
src = _gwrlsrc(fsrc);
newflags = 0;
if(!flisset(src->flags,GWRL_ENABLED)) {
fsrc = _gwrlsrcf(src->next);
continue;
}
if(FD_ISSET(fsrc->fd,&fds[0])) flset(newflags,GWRL_RD);
if(FD_ISSET(fsrc->fd,&fds[1])) flset(newflags,GWRL_WR);
if(FD_ISSET(fsrc->fd,&fds[2])) flset(newflags,GWRL_RD);
if(newflags > 0) {
evt = gwrl_evt_createp(rl,src,src->callback,src->userdata,fsrc->fd,newflags);
gwrl_post_evt(rl,evt);
}
fsrc = _gwrlsrcf(src->next);
}
}
}
示例3: read
//.........这里部分代码省略.........
// cursor doesn't reflect actual length of the string that's sent back
tty_con.cursor = strlen( tty_con.buffer );
if ( tty_con.cursor > 0 ) {
if ( tty_con.buffer[0] == '\\' ) {
for ( i = 0; i <= tty_con.cursor; i++ )
{
tty_con.buffer[i] = tty_con.buffer[i + 1];
}
tty_con.cursor--;
}
}
tty_Show();
return NULL;
}
avail = read( 0, &key, 1 );
if ( avail != -1 ) {
// VT 100 keys
if ( key == '[' || key == 'O' ) {
avail = read( 0, &key, 1 );
if ( avail != -1 ) {
switch ( key )
{
case 'A':
history = Hist_Prev();
if ( history ) {
tty_Hide();
tty_con = *history;
tty_Show();
}
tty_FlushIn();
return NULL;
break;
case 'B':
history = Hist_Next();
tty_Hide();
if ( history ) {
tty_con = *history;
} else
{
Field_Clear( &tty_con );
}
tty_Show();
tty_FlushIn();
return NULL;
break;
case 'C':
return NULL;
case 'D':
return NULL;
}
}
}
}
Com_DPrintf( "droping ISCTL sequence: %d, tty_erase: %d\n", key, tty_erase );
tty_FlushIn();
return NULL;
}
// push regular character
tty_con.buffer[tty_con.cursor] = key;
tty_con.cursor++;
// print the current line (this is differential)
write( 1, &key, 1 );
}
return NULL;
} else
{
int len;
fd_set fdset;
struct timeval timeout;
if ( !com_dedicated || !com_dedicated->value ) {
return NULL;
}
if ( !stdin_active ) {
return NULL;
}
FD_ZERO( &fdset );
FD_SET( 0, &fdset ); // stdin
timeout.tv_sec = 0;
timeout.tv_usec = 0;
if ( select( 1, &fdset, NULL, NULL, &timeout ) == -1 || !FD_ISSET( 0, &fdset ) ) {
return NULL;
}
len = read( 0, text, sizeof( text ) );
if ( len == 0 ) { // eof!
stdin_active = qfalse;
return NULL;
}
if ( len < 1 ) {
return NULL;
}
text[len - 1] = 0; // rip off the /n and terminate
return text;
}
}
示例4: PAUDIO_WaitDevice
/* This function waits until it is possible to write a full sound buffer */
static void
PAUDIO_WaitDevice(_THIS)
{
fd_set fdset;
/* See if we need to use timed audio synchronization */
if (this->hidden->frame_ticks) {
/* Use timer for general audio synchronization */
Sint32 ticks;
ticks =
((Sint32) (this->hidden->next_frame - SDL_GetTicks())) -
FUDGE_TICKS;
if (ticks > 0) {
SDL_Delay(ticks);
}
} else {
audio_buffer paud_bufinfo;
/* Use select() for audio synchronization */
struct timeval timeout;
FD_ZERO(&fdset);
FD_SET(this->hidden->audio_fd, &fdset);
if (ioctl(this->hidden->audio_fd, AUDIO_BUFFER, &paud_bufinfo) < 0) {
#ifdef DEBUG_AUDIO
fprintf(stderr, "Couldn't get audio buffer information\n");
#endif
timeout.tv_sec = 10;
timeout.tv_usec = 0;
} else {
long ms_in_buf = paud_bufinfo.write_buf_time;
timeout.tv_sec = ms_in_buf / 1000;
ms_in_buf = ms_in_buf - timeout.tv_sec * 1000;
timeout.tv_usec = ms_in_buf * 1000;
#ifdef DEBUG_AUDIO
fprintf(stderr,
"Waiting for write_buf_time=%ld,%ld\n",
timeout.tv_sec, timeout.tv_usec);
#endif
}
#ifdef DEBUG_AUDIO
fprintf(stderr, "Waiting for audio to get ready\n");
#endif
if (select(this->hidden->audio_fd + 1, NULL, &fdset, NULL, &timeout)
<= 0) {
const char *message =
"Audio timeout - buggy audio driver? (disabled)";
/*
* In general we should never print to the screen,
* but in this case we have no other way of letting
* the user know what happened.
*/
fprintf(stderr, "SDL: %s - %s\n", strerror(errno), message);
this->enabled = 0;
/* Don't try to close - may hang */
this->hidden->audio_fd = -1;
#ifdef DEBUG_AUDIO
fprintf(stderr, "Done disabling audio\n");
#endif
}
#ifdef DEBUG_AUDIO
fprintf(stderr, "Ready!\n");
#endif
}
}
示例5: wi_socket_wait_multiple
wi_socket_t * wi_socket_wait_multiple(wi_array_t *array, wi_time_interval_t timeout) {
wi_enumerator_t *enumerator;
wi_socket_t *socket, *waiting_socket = NULL;
struct timeval tv;
fd_set rfds, wfds;
int state, max_sd;
tv = wi_dtotv(timeout);
max_sd = -1;
FD_ZERO(&rfds);
FD_ZERO(&wfds);
wi_array_rdlock(array);
enumerator = wi_array_data_enumerator(array);
while((socket = wi_enumerator_next_data(enumerator))) {
if(wi_string_length(socket->buffer) > 0) {
waiting_socket = socket;
break;
}
if(socket->direction & WI_SOCKET_READ)
FD_SET(socket->sd, &rfds);
if(socket->direction & WI_SOCKET_WRITE)
FD_SET(socket->sd, &wfds);
if(socket->sd > max_sd)
max_sd = socket->sd;
}
wi_array_unlock(array);
if(waiting_socket)
return waiting_socket;
state = select(max_sd + 1, &rfds, &wfds, NULL, (timeout > 0.0) ? &tv : NULL);
if(state < 0) {
wi_error_set_errno(errno);
return NULL;
}
wi_array_rdlock(array);
enumerator = wi_array_data_enumerator(array);
while((socket = wi_enumerator_next_data(enumerator))) {
if(FD_ISSET(socket->sd, &rfds) || FD_ISSET(socket->sd, &wfds)) {
waiting_socket = socket;
break;
}
}
wi_array_unlock(array);
return waiting_socket;
}
示例6: easylink_thread
void easylink_thread(void *inContext)
{
OSStatus err = kNoErr;
mico_Context_t *Context = inContext;
fd_set readfds;
int reConnCount = 0;
int clientFdIsSet;
easylink_log_trace();
require_action(easylink_sem, threadexit, err = kNotPreparedErr);
if(Context->flashContentInRam.micoSystemConfig.easyLinkByPass == EASYLINK_BYPASS){
Context->flashContentInRam.micoSystemConfig.easyLinkByPass = EASYLINK_BYPASS_NO;
MICOUpdateConfiguration(Context);
_easylinkConnectWiFi_fast(Context);
}else if(Context->flashContentInRam.micoSystemConfig.easyLinkByPass == EASYLINK_SOFT_AP_BYPASS){
ConfigWillStop( Context );
_easylinkStartSoftAp(Context);
mico_rtos_delete_thread(NULL);
return;
}else{
#ifdef EasyLink_Plus
easylink_log("Start easylink plus mode");
micoWlanStartEasyLinkPlus(EasyLink_TimeOut/1000);
#else
easylink_log("Start easylink V2");
micoWlanStartEasyLink(EasyLink_TimeOut/1000);
#endif
mico_rtos_get_semaphore(&easylink_sem, MICO_WAIT_FOREVER);
if(EasylinkFailed == false)
_easylinkConnectWiFi(Context);
else{
msleep(20);
_cleanEasyLinkResource( Context );
ConfigWillStop( Context );
_easylinkStartSoftAp(Context);
mico_rtos_delete_thread(NULL);
return;
}
}
err = mico_rtos_get_semaphore(&easylink_sem, EasyLink_ConnectWlan_Timeout);
require_noerr(err, reboot);
httpHeader = HTTPHeaderCreate();
require_action( httpHeader, threadexit, err = kNoMemoryErr );
HTTPHeaderClear( httpHeader );
while(1){
if(easylinkClient_fd == -1){
err = _connectFTCServer(inContext, &easylinkClient_fd);
require_noerr(err, Reconn);
}else{
FD_ZERO(&readfds);
FD_SET(easylinkClient_fd, &readfds);
if(httpHeader->len == 0){
err = select(1, &readfds, NULL, NULL, NULL);
require(err>=1, threadexit);
clientFdIsSet = FD_ISSET(easylinkClient_fd, &readfds);
}
if(clientFdIsSet||httpHeader->len){
err = SocketReadHTTPHeader( easylinkClient_fd, httpHeader );
switch ( err )
{
case kNoErr:
// Read the rest of the HTTP body if necessary
do{
err = SocketReadHTTPBody( easylinkClient_fd, httpHeader );
require_noerr(err, Reconn);
PrintHTTPHeader(httpHeader);
// Call the HTTPServer owner back with the acquired HTTP header
err = _FTCRespondInComingMessage( easylinkClient_fd, httpHeader, Context );
require_noerr( err, Reconn );
if(httpHeader->contentLength == 0)
break;
} while( httpHeader->chunkedData == true || httpHeader->dataEndedbyClose == true);
// Reuse HTTPHeader
HTTPHeaderClear( httpHeader );
break;
case EWOULDBLOCK:
// NO-OP, keep reading
break;
case kNoSpaceErr:
easylink_log("ERROR: Cannot fit HTTPHeader.");
goto Reconn;
break;
case kConnectionErr:
// NOTE: kConnectionErr from SocketReadHTTPHeader means it's closed
easylink_log("ERROR: Connection closed.");
/*Roll back to previous settings (if it has) and reboot*/
if(Context->flashContentInRam.micoSystemConfig.configured == wLanUnConfigured ){
Context->flashContentInRam.micoSystemConfig.configured = allConfigured;
MICOUpdateConfiguration( Context );
//.........这里部分代码省略.........
示例7: p2p_log_msg
//
// function: tunnel_server_handler
// opne a service port and process the service request from devices
// parameters
// service port number
// return
// 0 success
// other fail
//
void *tunnel_server_handler(void *pdata)
{
fd_set readfds, writefds, rfds, wfds;
int nfds=-1,servfd=-1, sd=-1, ret=-1;
struct timeval tv;
struct sockaddr_in clientaddr; /* client addr */
int optval; /* service socket */
unsigned int next_time, current_time;
#ifdef _OPEN_SECURED_CONN
SSL *ssl=NULL;
int securefd = -1;
#endif
//
// tunnel control block init
//
if (tunnel_ctrl_init()<0)
{
p2p_log_msg( "initial tunnel control block fail!");
goto end_tunnel_server_handler;
}
FD_ZERO(&readfds);
FD_ZERO(&writefds);
// wait mone secure connection
servfd = do_bind_service_port(service_port);
if (servfd>=0)
{
FD_SET(servfd, &readfds);
nfds = (servfd>nfds?servfd:nfds);
}
else
goto end_tunnel_server_handler;
#ifdef _OPEN_SECURED_CONN
// wait mone secure connection
securefd = do_bind_service_port(secure_service_port);
if (securefd>=0)
{
FD_SET(securefd, &readfds);
nfds = (securefd>nfds?securefd:nfds);
}
else
goto end_tunnel_server_handler;
#endif
//
// report to SC that service start
//
do_service_start("tunnel server start");
//
// main loop: wait for a connection request
//
current_time = get_time_milisec();
next_time = current_time + 10000; // next seconds
while (tunnel_server_on)
{
current_time = get_time_milisec();
if (current_time > next_time)
{
// if timer expired, do report to SC
do_service_report();
next_time = current_time + 10000; // 10 seconds
}
memcpy(&rfds,&readfds,sizeof(fd_set));
memcpy(&wfds,&writefds,sizeof(fd_set));
// reset timeout value
tv.tv_sec = 1; // 1 seconds
tv.tv_usec = 0;
if((ret=select(nfds+1, &rfds, &wfds, NULL, &tv)) == -1)
{
p2p_log_msg( "Server-select() error lol!");
goto end_tunnel_server_handler;
}
#ifdef _OPEN_SECURED_CONN
if (FD_ISSET(securefd, &rfds))
{
socklen_t clientlen = sizeof(clientaddr);
sd = ssl_server_accept(securefd,&ssl);
if (sd >= 0)
{
getpeername(sd, (struct sockaddr*)&clientaddr, &clientlen);
p2p_log_msg("new secure connection from %s\n",inet_ntoa (clientaddr.sin_addr));
ret = new_device_tunnel(sd, &clientaddr, ssl);
if (ret<0)
{
p2p_log_msg("reject secure connection from %s\n",inet_ntoa (clientaddr.sin_addr));
ssl_server_close(ssl);
}
}
//.........这里部分代码省略.........
示例8: ARGS1
/* Bind to a TCP port
** ------------------
**
** On entry,
** tsap is a string explaining where to take data from.
** "" means data is taken from stdin.
** "*:1729" means "listen to anyone on port 1729"
**
** On exit,
** returns Negative value if error.
*/
int do_bind ARGS1(CONST char *, tsap)
{
FD_ZERO(&open_sockets); /* Clear our record of open sockets */
num_sockets = 0;
/* Deal with PASSIVE socket:
**
** A passive TSAP is one which has been created by the inet daemon.
** It is indicated by a void TSAP name. In this case, the inet
** daemon has started this process and given it, as stdin, the connection
** which it is to use.
*/
if (*tsap == 0) { /* void tsap => passive */
dynamic_allocation = FALSE; /* not dynamically allocated */
role = passive; /* Passive: started by daemon */
#ifdef vms
{ unsigned short channel; /* VMS I/O channel */
struct string_descriptor { /* This is NOT a proper descriptor*/
int size; /* but it will work. */
char *ptr; /* Should be word,byte,byte,long */
} sys_input = {10, "SYS$INPUT:"};
int status; /* Returned status of assign */
extern int sys$assign();
status = sys$assign(&sys_input, &channel, 0, 0);
com_soc = channel; /* The channel is stdin */
CTRACE(tfp, "IP: Opened PASSIVE socket %d\n", channel);
return 1 - (status&1);
}
#else
com_soc = 0; /* The channel is stdin */
CTRACE(tfp, "IP: PASSIVE socket 0 assumed from inet daemon\n");
return 0; /* Good */
#endif
/* Parse the name (if not PASSIVE)
*/
} else { /* Non-void TSAP */
char *p; /* pointer to string */
char *q;
struct hostent *phost; /* Pointer to host - See netdb.h */
char buffer[256]; /* One we can play with */
register struct sockaddr_in* sin = &soc_address;
strcpy(buffer, tsap);
p = buffer;
/* Set up defaults:
*/
sin->sin_family = AF_INET; /* Family = internet, host order */
sin->sin_port = 0; /* Default: new port, */
dynamic_allocation = TRUE; /* dynamically allocated */
role = passive; /* by default */
/* Check for special characters:
*/
if (*p == WILDCARD) { /* Any node */
role = master;
p++;
}
/* Strip off trailing port number if any:
*/
for(q=p; *q; q++)
if (*q==':') {
int status;
*q++ = 0; /* Terminate node string */
sin->sin_port = htons((unsigned short)HTCardinal(
&status, &q, (unsigned int)65535));
if (status<0) return status;
if (*q) return -2; /* Junk follows port number */
dynamic_allocation = FALSE;
break; /* Exit for loop before we skip the zero */
} /*if*/
/* Get node name:
*/
if (*p == 0) {
sin->sin_addr.s_addr = INADDR_ANY; /* Default: any address */
} else if (*p>='0' && *p<='9') { /* Numeric node address: */
sin->sin_addr.s_addr = inet_addr(p); /* See arpa/inet.h */
} else { /* Alphanumeric node name: */
//.........这里部分代码省略.........
示例9: server_loop
PRIVATE int server_loop()
#endif
{
int tcp_status; /* <0 if error, in general */
int timeout = -1; /* No timeout required but code exists */
for(;;) {
/* If it's a master socket, then find a slave:
*/
if (role == master) {
#ifdef SELECT
fd_set read_chans;
fd_set write_chans;
fd_set except_chans;
int nfound; /* Number of ready channels */
struct timeval max_wait; /* timeout in form for select() */
FD_ZERO(&write_chans); /* Clear the write mask */
FD_ZERO(&except_chans); /* Clear the exception mask */
/* If timeout is required, the timeout structure is set up. Otherwise
** (timeout<0) a zero is passed instead of a pointer to the struct timeval.
*/
if (timeout>=0) {
max_wait.tv_sec = timeout/100;
max_wait.tv_usec = (timeout%100)*10000;
}
for (com_soc=(-1); com_soc<0;) { /* Loop while connections keep coming */
/* The read mask expresses interest in the master channel for incoming
** connections) or any slave channel (for incoming messages).
*/
/* Wait for incoming connection or message
*/
read_chans = open_sockets; /* Read on all active channels */
if (TRACE) printf(
"Daemon: Waiting for connection or message. (Mask=%x hex, max=%x hex).\n",
*(int *)(&read_chans), num_sockets);
nfound=select(num_sockets, &read_chans,
&write_chans, &except_chans,
timeout >= 0 ? &max_wait : 0);
if (nfound<0) return HTInetStatus("select()");
if (nfound==0) return 0; /* Timeout */
/* We give priority to existing connected customers. When there are
** no outstanding commands from them, we look for new customers.
*/
/* If a message has arrived on one of the channels, take that channel:
*/
{
int i;
for(i=0; i<num_sockets; i++)
if (i != master_soc)
if (FD_ISSET(i, &read_chans)) {
if (TRACE) printf(
"Message waiting on socket %d\n", i);
com_soc = i; /* Got one! */
break;
}
if (com_soc>=0) break; /* Found input socket */
} /* block */
/* If an incoming connection has arrived, accept the new socket:
*/
if (FD_ISSET(master_soc, &read_chans)) {
CTRACE(tfp, "Daemon: New incoming connection:\n");
tcp_status = accept(master_soc,
(struct sockaddr *)&soc_address,
&soc_addrlen);
if (tcp_status<0)
return HTInetStatus("accept");
CTRACE(tfp, "Daemon: Accepted new socket %d\n",
tcp_status);
FD_SET(tcp_status, &open_sockets);
if ((tcp_status+1) > num_sockets)
num_sockets=tcp_status+1;
} /* end if new connection */
} /* loop on event */
#else /* SELECT not supported */
if (com_soc<0) { /* No slaves: must accept */
CTRACE(tfp,
"Daemon: Waiting for incoming connection...\n");
tcp_status = accept(master_soc,
&rsoc->mdp.soc_tcp.soc_address,
&rsoc->mdp.soc_tcp.soc_addrlen);
if (tcp_status<0)
return HTInetStatus("accept");
com_soc = tcp_status; /* socket number */
CTRACE(tfp, "Daemon: Accepted socket %d\n", tcp_status);
//.........这里部分代码省略.........
示例10: cmyth_file_read
/*
* cmyth_file_read()
*
* Scope: PUBLIC
*
* Description
*
* Request and read a block of data from backend
*
* Return Value:
*
* Sucess: number of bytes transfered
*
* Failure: an int containing -errno
*/
int32_t cmyth_file_read(cmyth_file_t file, char *buf, int32_t len)
{
int err, count;
int32_t ret;
int req, nfds, rec;
char *end, *cur;
char msg[256];
int64_t len64;
struct timeval tv;
fd_set fds;
if (!file || !file->file_data) {
cmyth_dbg (CMYTH_DBG_ERROR, "%s: no connection\n",
__FUNCTION__);
return -EINVAL;
}
if (len == 0)
return 0;
if(len > file->file_data->conn_tcp_rcvbuf)
len = file->file_data->conn_tcp_rcvbuf;
pthread_mutex_lock (&file->file_control->conn_mutex);
/* make sure we have outstanding requests that fill the buffer that was called with */
/* this way we should be able to saturate the network connection better */
if (file->file_req < file->file_pos + len) {
snprintf (msg, sizeof (msg),
"QUERY_FILETRANSFER %"PRIu32"[]:[]REQUEST_BLOCK[]:[]%"PRId32,
file->file_id, (int32_t)(file->file_pos + len - file->file_req));
if ( (err = cmyth_send_message (file->file_control, msg) ) < 0) {
cmyth_dbg (CMYTH_DBG_ERROR,
"%s: cmyth_send_message() failed (%d)\n",
__FUNCTION__, err);
ret = err;
goto out;
}
req = 1;
} else {
req = 0;
}
rec = 0;
cur = buf;
end = buf+len;
while (cur == buf || req || rec) {
if(rec) {
tv.tv_sec = 0;
tv.tv_usec = 0;
} else {
tv.tv_sec = 20;
tv.tv_usec = 0;
}
nfds = 0;
FD_ZERO (&fds);
if (req) {
if ((int)file->file_control->conn_fd > nfds)
nfds = (int)file->file_control->conn_fd;
FD_SET (file->file_control->conn_fd, &fds);
}
if ((int)file->file_data->conn_fd > nfds)
nfds = (int)file->file_data->conn_fd;
FD_SET (file->file_data->conn_fd, &fds);
if ((ret = select (nfds+1, &fds, NULL, NULL,&tv)) < 0) {
cmyth_dbg (CMYTH_DBG_ERROR,
"%s: select(() failed (%d)\n",
__FUNCTION__, ret);
goto out;
}
if (ret == 0 && !rec) {
file->file_control->conn_hang = 1;
file->file_data->conn_hang = 1;
ret = -ETIMEDOUT;
goto out;
}
/* check control connection */
if (FD_ISSET(file->file_control->conn_fd, &fds)) {
//.........这里部分代码省略.........
示例11: main_loop
/*
* main loop: listen on stdin (for user input) and master pty (for command output),
* and try to write output_queue to master_pty (if it is not empty)
* This function never returns.
*/
void
main_loop()
{
int nfds;
fd_set readfds;
fd_set writefds;
int nread;
char buf[BUFFSIZE], *timeoutstr, *old_raw_prompt, *new_output_minus_prompt;
int promptlen = 0;
int leave_prompt_alone;
sigset_t no_signals_blocked;
int seen_EOF = FALSE;
struct timespec select_timeout, *select_timeoutptr;
struct timespec immediately = { 0, 0 }; /* zero timeout when child is dead */
struct timespec wait_a_little = {0, 0xBadf00d }; /* tv_usec field will be filled in when initialising */
struct timespec *forever = NULL;
wait_a_little.tv_nsec = 1000 * 1000 * wait_before_prompt;
sigemptyset(&no_signals_blocked);
init_readline("");
last_minute_checks();
pass_through_filter(TAG_OUTPUT,""); /* If something is wrong with filter, get the error NOW */
set_echo(FALSE); /* This will also put the terminal in CBREAK mode */
test_main();
/* ------------------------------ main loop -------------------------------*/
while (TRUE) {
/* listen on both stdin and pty_fd */
FD_ZERO(&readfds);
FD_SET(STDIN_FILENO, &readfds);
FD_SET(master_pty_fd, &readfds);
/* try to write output_queue to master_pty (but only if it is nonempty) */
FD_ZERO(&writefds);
if (output_queue_is_nonempty())
FD_SET(master_pty_fd, &writefds);
DPRINTF1(DEBUG_AD_HOC, "prompt_is_still_uncooked = %d", prompt_is_still_uncooked);
if (command_is_dead || ignore_queued_input) {
select_timeout = immediately;
select_timeoutptr = &select_timeout;
timeoutstr = "immediately";
} else if (prompt_is_still_uncooked || polling) {
select_timeout = wait_a_little;
select_timeoutptr = &select_timeout;
timeoutstr = "wait_a_little";
} else {
select_timeoutptr = forever; /* NULL */
timeoutstr = "forever";
}
DPRINTF1(DEBUG_TERMIO, "calling select() with timeout %s", timeoutstr);
nfds = my_pselect(1 + master_pty_fd, &readfds, &writefds, NULL, select_timeoutptr, &no_signals_blocked);
DPRINTF3(DEBUG_TERMIO, "select() returned %d (stdin|pty in|pty out = %03d), within_line_edit=%d", nfds,
100*(FD_ISSET(STDIN_FILENO, &readfds)?1:0) + 10*(FD_ISSET(master_pty_fd, &readfds)?1:0) + (FD_ISSET(master_pty_fd, &writefds)?1:0),
within_line_edit);
assert(!filter_pid || filter_is_dead || kill(filter_pid,0) == 0);
assert(command_is_dead || kill(command_pid,0) == 0);
/* check flags that may have been set by signal handlers */
if (filter_is_dead)
filters_last_words(); /* will call myerror with last words */
if (received_WINCH) { /* received_WINCH flag means we've had a WINCH while within_line_edit was FALSE */
DPRINTF0(DEBUG_READLINE, "Starting line edit as a result of WINCH ");
within_line_edit = TRUE;
restore_rl_state();
received_WINCH = FALSE;
continue;
}
if (nfds < 0) { /* exception */
if (errno == EINTR || errno == 0) { /* interrupted by signal, or by a cygwin bug (errno == 0) :-( */
continue;
} else
myerror(FATAL|USE_ERRNO, "select received exception");
} else if (nfds == 0) {
/* timeout, which can only happen when .. */
if (ignore_queued_input) { /* ... we have read all the input keystrokes that should
be ignored (i.e. those that accumulated on stdin while we
were calling an external editor) */
ignore_queued_input = FALSE;
continue;
//.........这里部分代码省略.........
示例12: main
main(int argc,char *argv[])
{
CoolImage *image;
int x,y;
int i,j;
PtWidget_t *win;
PtArg_t args[3];
PhDim_t dim={m_W,m_H};
PhPoint_t pos={50,250};
int fd; //Bt878 driver file descriptor
int fd_temp;
int size_read;
struct timeval tv;
fd_set rfd;
int n;
int error;
int counter = 0;
int counter_mean = 0;
int file = 0;
//Timing calculation
uint64_t cps, cycle1, cycle2, ncycles;
float sec;
float msec;
// if a paramater was passed, grab it as the blit type
if (argc>1) blittype=atoi(argv[1]);
// initialize our connection to Photon, and create/realize a window
//PtInit("/net/irene2/dev/photon");
PtInit("/dev/photon");
PtSetArg(&args[0],Pt_ARG_POS,&pos,0);
PtSetArg(&args[1],Pt_ARG_DIM,&dim,0);
win=PtCreateWidget(PtWindow,Pt_NO_PARENT,2,args);
PtRealizeWidget(win);
// Allocate and fill a series of NUMIMAGES images with a little
// fading type animation. Put your own animation in here if you like.
/*
* Set a 5 second timeout.
*/
tv.tv_sec = 5;
tv.tv_usec = 0;
image = AllocBuffer(m_W,m_H,fd);
assert(image!=0);
if (file != 2)
{
init_bttvx(2,0, m_W,m_H,0,0);
open_bttvx();
BttvxSetImageBuffer(0, image->buffer);
}
fd_temp = fd;
FD_ZERO( &rfd );
FD_SET( fd, &rfd );
while(1)
{
//fd = open("/net/europa/dev/bttvx0",O_RDWR);
//if ( fd > 0 )
//{
///switch ( n = select( 1 + max( fd,0 ),
/// &rfd, 0, 0, &tv ) )
///{
/// case -1:
/// perror( "select" );
/// return EXIT_FAILURE;
/// case 0:
/// puts( "select timed out" );
/// break;
/// default:
//printf( "descriptor ready ...\n");
//if( FD_ISSET( console, &rfd ) )
// puts( " -- console descriptor has data pending" );
//if( FD_ISSET( serial, &rfd ) )
// puts( " -- serial descriptor has data pending" );
/* Read the text */
cycle1=ClockCycles( );
//lseek(fd,0L,SEEK_SET);
/// size_read = read( fd, image->buffer, W*H*deep );
if (file != 2)
{
BttvxWaitEvent();
BttvxAcquireBuffer(image->buffer);
}
switch(file)
{
case 0:
BlitBuffer(win,image);
break;
//.........这里部分代码省略.........
示例13: main
/*
* Simply download a HTTP file.
*/
int main(int argc, char **argv)
{
CURL *http_handle;
CURLM *multi_handle;
int still_running; /* keep number of running handles */
http_handle = curl_easy_init();
/* set the options (I left out a few, you'll get the point anyway) */
curl_easy_setopt(http_handle, CURLOPT_URL, "http://www.haxx.se/");
curl_easy_setopt(http_handle, CURLOPT_DEBUGFUNCTION, my_trace);
curl_easy_setopt(http_handle, CURLOPT_VERBOSE, 1L);
/* init a multi stack */
multi_handle = curl_multi_init();
/* add the individual transfers */
curl_multi_add_handle(multi_handle, http_handle);
/* we start some action by calling perform right away */
while(CURLM_CALL_MULTI_PERFORM ==
curl_multi_perform(multi_handle, &still_running));
while(still_running) {
struct timeval timeout;
int rc; /* select() return code */
fd_set fdread;
fd_set fdwrite;
fd_set fdexcep;
int maxfd = -1;
FD_ZERO(&fdread);
FD_ZERO(&fdwrite);
FD_ZERO(&fdexcep);
/* set a suitable timeout to play around with */
timeout.tv_sec = 1;
timeout.tv_usec = 0;
/* get file descriptors from the transfers */
curl_multi_fdset(multi_handle, &fdread, &fdwrite, &fdexcep, &maxfd);
/* In a real-world program you OF COURSE check the return code of the
function calls. On success, the value of maxfd is guaranteed to be
greater or equal than -1. We call select(maxfd + 1, ...), specially in
case of (maxfd == -1), we call select(0, ...), which is basically equal
to sleep. */
rc = select(maxfd+1, &fdread, &fdwrite, &fdexcep, &timeout);
switch(rc) {
case -1:
/* select error */
still_running = 0;
printf("select() returns error, this is badness\n");
break;
case 0:
default:
/* timeout or readable/writable sockets */
while(CURLM_CALL_MULTI_PERFORM ==
curl_multi_perform(multi_handle, &still_running));
break;
}
}
curl_multi_cleanup(multi_handle);
curl_easy_cleanup(http_handle);
return 0;
}
示例14: test
//.........这里部分代码省略.........
curl_easy_setopt(c, CURLOPT_PROXY, arg2);
curl_easy_setopt(c, CURLOPT_URL, URL);
curl_easy_setopt(c, CURLOPT_VERBOSE, 1);
if ((m = curl_multi_init()) == NULL) {
fprintf(stderr, "curl_multi_init() failed\n");
curl_easy_cleanup(c);
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
if ((res = curl_multi_add_handle(m, c)) != CURLM_OK) {
fprintf(stderr, "curl_multi_add_handle() failed, "
"with code %d\n", res);
curl_multi_cleanup(m);
curl_easy_cleanup(c);
curl_global_cleanup();
return TEST_ERR_MAJOR_BAD;
}
ml_timedout = FALSE;
ml_start = tutil_tvnow();
while (!done) {
struct timeval interval;
interval.tv_sec = 1;
interval.tv_usec = 0;
if (tutil_tvdiff(tutil_tvnow(), ml_start) >
MAIN_LOOP_HANG_TIMEOUT) {
ml_timedout = TRUE;
break;
}
mp_timedout = FALSE;
mp_start = tutil_tvnow();
fprintf(stderr, "curl_multi_perform()\n");
res = CURLM_CALL_MULTI_PERFORM;
while (res == CURLM_CALL_MULTI_PERFORM) {
res = curl_multi_perform(m, &running);
if (tutil_tvdiff(tutil_tvnow(), mp_start) >
MULTI_PERFORM_HANG_TIMEOUT) {
mp_timedout = TRUE;
break;
}
}
if (mp_timedout)
break;
if(!running) {
/* This is where this code is expected to reach */
int numleft;
CURLMsg *msg = curl_multi_info_read(m, &numleft);
fprintf(stderr, "Expected: not running\n");
if(msg && !numleft)
ret = 100; /* this is where we should be */
else
ret = 99; /* not correct */
break;
}
fprintf(stderr, "running == %d, res == %d\n", running, res);
if (res != CURLM_OK) {
ret = 2;
break;
}
FD_ZERO(&rd);
FD_ZERO(&wr);
FD_ZERO(&exc);
max_fd = 0;
fprintf(stderr, "curl_multi_fdset()\n");
if (curl_multi_fdset(m, &rd, &wr, &exc, &max_fd) != CURLM_OK) {
fprintf(stderr, "unexpected failured of fdset.\n");
ret = 3;
break;
}
rc = select_test(max_fd+1, &rd, &wr, &exc, &interval);
fprintf(stderr, "select returned %d\n", rc);
}
if (ml_timedout || mp_timedout) {
if (ml_timedout) fprintf(stderr, "ml_timedout\n");
if (mp_timedout) fprintf(stderr, "mp_timedout\n");
fprintf(stderr, "ABORTING TEST, since it seems "
"that it would have run forever.\n");
ret = TEST_ERR_RUNS_FOREVER;
}
curl_multi_remove_handle(m, c);
curl_easy_cleanup(c);
curl_multi_cleanup(m);
curl_global_cleanup();
return ret;
}
示例15: redisContextWaitReady
static int redisContextWaitReady(redisContext *c, const struct timeval *timeout) {
#ifdef FASTO
#ifdef OS_WIN
fd_set master_set;
FD_ZERO(&master_set);
int max_sd = c->fd;
FD_SET(c->fd, &master_set);
struct timeval tm;
tm.tv_sec = 60;
tm.tv_usec = 0;
/* Only use timeout when not NULL. */
if (timeout != NULL) {
if (timeout->tv_usec > 1000000 || timeout->tv_sec > __MAX_MSEC) {
redisContextCloseFd(c);
return REDIS_ERR;
}
tm = *timeout;
}
if (errno == EINPROGRESS) {
int res;
if ((res = select(max_sd + 1, &master_set, NULL, NULL, &tm)) == -1) {
__redisSetErrorFromErrno(c, REDIS_ERR_IO, "select(2)");
redisContextCloseFd(c);
return REDIS_ERR;
} else if (res == 0) {
errno = ETIMEDOUT;
__redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
redisContextCloseFd(c);
return REDIS_ERR;
}
if (redisCheckSocketError(c) != REDIS_OK)
return REDIS_ERR;
return REDIS_OK;
}
__redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
redisContextCloseFd(c);
return REDIS_ERR;
#else
struct pollfd wfd[1];
long msec;
msec = -1;
wfd[0].fd = c->fd;
wfd[0].events = POLLOUT;
/* Only use timeout when not NULL. */
if (timeout != NULL) {
if (timeout->tv_usec > 1000000 || timeout->tv_sec > __MAX_MSEC) {
__redisSetErrorFromErrno(c, REDIS_ERR_IO, NULL);
redisContextCloseFd(c);
return REDIS_ERR;
}
msec = (timeout->tv_sec * 1000) + ((timeout->tv_usec + 999) / 1000);
if (msec < 0 || msec > INT_MAX) {
msec = INT_MAX;
}
}
if (errno == EINPROGRESS) {
int res;
if ((res = poll(wfd, 1, msec)) == -1) {
__redisSetErrorFromErrno(c, REDIS_ERR_IO, "poll(2)");
redisContextCloseFd(c);
return REDIS_ERR;
} else if (res == 0) {
errno = ETIMEDOUT;
__redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
redisContextCloseFd(c);
return REDIS_ERR;
}
if (redisCheckSocketError(c) != REDIS_OK)
return REDIS_ERR;
return REDIS_OK;
}
__redisSetErrorFromErrno(c,REDIS_ERR_IO,NULL);
redisContextCloseFd(c);
return REDIS_ERR;
#endif
#else
struct pollfd wfd[1];
long msec;
msec = -1;
wfd[0].fd = c->fd;
wfd[0].events = POLLOUT;
/* Only use timeout when not NULL. */
//.........这里部分代码省略.........