以下只是使用fcntl改变标准输入的阻塞模式,改成非阻塞的模式
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
char buffer[1024] = {0};
int flags;
flags = fcntl(STDIN_FILENO, F_GETFL);
flags |= O_NONBLOCK;
if ( fcntl(STDIN_FILENO, F_SETFL, flags) < 0 )
{
perror("fcntl");
return -1;
}
while (1)
{
memset(buffer, 0, sizeof(buffer));
ssize_t size = read(STDIN_FILENO, buffer, sizeof(buffer));
if ( size < 0 )
{
if (errno == EAGAIN )
{
printf("try again\n");
sleep(1);
continue;
}
perror("read");
break;
}
if ( size == 0 )
{
printf("end of file\n");
break;
}
write(STDOUT_FILENO, buffer, size);
}
return 0;
}