Skip to content

Instantly share code, notes, and snippets.

@ityuhui
Last active April 13, 2021 12:52
Show Gist options
  • Save ityuhui/fca8185057eaf765fad27123aafa69fb to your computer and use it in GitHub Desktop.
Save ityuhui/fca8185057eaf765fad27123aafa69fb to your computer and use it in GitHub Desktop.
C non-block read from stdion
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <memory.h>
#define WSC_ATTACH_STDIN_BUFFER_SIZE 1024
int main()
{
char wsc_attach_stdin_buffer[WSC_ATTACH_STDIN_BUFFER_SIZE] = {0};
#if 1
int flag;
flag = fcntl(STDIN_FILENO, F_GETFL);
flag |= O_NONBLOCK;
fcntl(STDIN_FILENO, F_SETFL, flag);
#endif
while(1)
{
if (strlen(wsc_attach_stdin_buffer) != 0) {
printf("%s", wsc_attach_stdin_buffer);
memset(wsc_attach_stdin_buffer, 0, sizeof(wsc_attach_stdin_buffer));
}
fgets(wsc_attach_stdin_buffer,sizeof(wsc_attach_stdin_buffer) -1,stdin);
sleep(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment