Вам нужно сделать дескриптор файла неблокирующим. Вы можете сделать это так:
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
Объяснение
Так работает fcntl
(не полное описание - посмотрите на man fcntl
). Прежде всего, включает в себя:
#include <unistd.h>
#include <fcntl.h>
чтение флагов дескриптора файла
Используйте F_GETFL
, чтобы получить флаги дескриптора файла. От man fcntl
:
F_GETFL
Read the file descriptor's flags.
RETURN VALUE
For a successful call, the return value depends on the operation:
F_GETFL Value of flags.
и вот как это используется:
int fd_flags = fcntl(fd, F_GETFL);
запись флагов дескриптора файла
Используйте F_SETFL
, чтобы установить флаг O_NONBLOCK
. Опять цитата из man fcntl
:
F_SETFL
Set the file status flags part of the descriptor's flags to the
value specified by arg. Remaining bits (access mode, file cre?
ation flags) in arg are ignored. On Linux this command can
only change the O_APPEND, O_NONBLOCK, O_ASYNC, and O_DIRECT
flags.
и вот как это используется:
fcntl(fd, F_SETFL, fd_flags | O_NONBLOCK);