linux 管道非阻塞,linux – 管道上的非阻塞读取

管道和O_NONBLOCK没有什么特别之处.以下示例按预期工作.我没有检查每次调用的每个retval,以使示例更具可读性.真实世界的应用程序必须进行检查.

#include

#include

#include

#include

int main()

{

int fds[2];

pid_t pid;

char buf[100];

pipe(fds);

pid = fork();

if ( pid )

{

while (1 )

{

memcpy( buf, "abcdefghi\0",10);

write( fds[1], buf, 10);

sleep(2);

}

}

else

{

int retval = fcntl( fds[0], F_SETFL, fcntl(fds[0], F_GETFL) | O_NONBLOCK);

printf("Ret from fcntl: %d\n", retval);

while (1)

{

ssize_t r=read( fds[0], buf, 10 );

printf("read: %d\n", r);

if ( r > 0 )

{

printf("Buffer: %s\n", buf);

}

else

{

printf("Read nothing\n");

perror("Error was");

sleep(1);

}

}

}

}

写完我的例子后,我检查你的代码,发现:

flags = fcntl(pfd[0], F_GETFD);

flags |= O_NONBLOCK;

if (fcntl(pfd[0], F_SETFD, flags))

请将F_SETFD更改为F_SETFL以及get操作.您不会更改文件描述符标志,但文件描述符状态标志:-)

来自man 3 fcntl:

File descriptor flags

The following commands manipulate the flags associated with a file

descriptor. Currently, only one such flag is defined: FD_CLOEXEC, the

close-on-exec flag. If the FD_CLOEXEC bit is 0, the file descriptor

will remain open across an execve(2), otherwise it will be closed.

File status flags

Each open file description has certain associated status flags, ini‐

tialized by open(2) and possibly modified by fcntl(). Duplicated file

descriptors (made with dup(2), fcntl(F_DUPFD), fork(2), etc.) refer to

the same open file description, and thus share the same file status

flags.

F_SETFL (int)

Set the file status flags to the value specified by arg. File

access mode (O_RDONLY, O_WRONLY, O_RDWR) and file creation flags

(i.e., O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC) in arg are ignored.

On Linux this command can change only the O_APPEND, O_ASYNC,

O_DIRECT, O_NOATIME, and O_NONBLOCK flags. It is not possible to change the O_DSYNC and O_SYNC flags; see BUGS, below.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值