Multi-task I/O select function

Source: Internet
Author: User
# Include <stdio. h>
# Include <sys/time. h>
# Include <sys/types. h>
# Include <unistd. h>

Int main (void ){
Struct timeval TV;
Fd_set readfds;
Int ret;

// Wait for stdin Input
Fd_zero (& readfds); // remove all
Fd_set (stdin_fileno, & readfds); // Add to group
// Fd_clr is used to remove

// Set the wait time
TV. TV _sec = 5;
TV. TV _usec = 0;

// The first parameter is the maximum number of the file descriptor plus 1
Ret = select (stdin_fileno + 1, & readfds, null, null, & TV );

If (ret =-1 ){
Perror ("select ");
Return 1;
} Else if (! RET ){
Printf ("time out \ n ");
Return 0;
}
// Check whether stdin_fileno can be read without being blocked.
If (fd_isset (stdin_fileno, & readfds )){
Char Buf [1025];
Int Len;
// It will not block
Len = read (stdin_fileno, Buf, 1024 );
If (LEN =-1 ){
Perror ("read ");
Return 1;
}
If (LEN ){
Buf [Len] = '\ 0 ';
Printf ("read: % s \ n", Buf );
}
Return 0;
}
Printf ("won't happen \ n ");
Return 1;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.