Linux 非阻塞管道

(图片来源网络,侵删)
Linux中的非阻塞管道是一种进程间通信机制,允许在没有数据可读或写时不阻塞进程,这提高了多任务处理的效率,特别是在实时性要求高的应用中。
设置非阻塞模式
1、获取文件描述符属性:使用fcntl(fd, F_GETFL)获取当前文件描述符的标志。
2、设置非阻塞标志:将O_NONBLOCK标志通过按位或运算添加到现有标志中,然后使用fcntl(fd, F_SETFL, flags)重新设置标志。
3、示例代码:

(图片来源网络,侵删)
#include <fcntl.h>
int set_nonblocking(int fd) {
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1) {
perror("fcntl get");
return -1;
}
flags |= O_NONBLOCK;
int result = fcntl(fd, F_SETFL, flags);
if (result == -1) {
perror("fcntl set");
return -1;
}
return 0;
} 非阻塞读写行为
| 操作 | 结果 | 说明 |
|------|------|-----|
| 读取 | 返回实际读取的字节数 | 如果管道中有数据可读<br>返回0 | 如果管道为空且写入端关闭<br>返回-1并设置errno为EAGAIN | 如果管道为空且写入端未关闭 |
| 写入 | 返回实际写入的字节数 | 如果管道有空间可用<br>返回-1并设置errno为EPIPE | 如果管道已满且读取端关闭<br>返回-1并设置errno为EAGAIN | 如果管道已满且读取端未关闭 |

(图片来源网络,侵删)
示例程序
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main() {
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
set_nonblocking(pipefd[0]);
set_nonblocking(pipefd[1]);
const char* msg = "Hello, Non-blocking Pipe!";
ssize_t n = write(pipefd[1], msg, strlen(msg));
if (n == -1) {
perror("write");
exit(EXIT_FAILURE);
}
char buffer[1024];
n = read(pipefd[0], buffer, sizeof(buffer));
if (n == -1) {
perror("read");
exit(EXIT_FAILURE);
} else if (n == 0) {
printf("Read end closed
");
} else {
buffer[n] = ' ';
printf("Read '%s' from pipe
", buffer);
}
close(pipefd[0]);
close(pipefd[1]);
return 0;
} 非阻塞管道编程是Linux下的一种重要技术,它允许进程在读写操作时不被阻塞,从而提高程序的性能,通过掌握非阻塞管道编程,可以更好地应对多线程环境下的并发读写问题。
小伙伴们,上文介绍linux 非阻塞管道的内容,你了解清楚吗?希望对你有所帮助,任何问题可以给我留言,让我们下期再见吧。
本文来源于互联网,如若侵权,请联系管理员删除,本文链接:https://www.9969.net/76364.html