要设置stdin(标准输入)为非阻塞模式和阻塞模式,并且仅对当前进程有效,我们可以使用fcntl
函数调整文件描述符的标志。以下是实现这两个功能的函数:
设置非阻塞模式
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
void setStdinNonBlocking(void) {
int flags = fcntl(STDIN_FILENO, F_GETFL, 0); // 获取当前flags
if (flags == -1) {
perror("fcntl - GETFL");
exit(EXIT_FAILURE);
}
flags |= O_NONBLOCK; // 添加非阻塞标志
if (fcntl(STDIN_FILENO, F_SETFL, flags) == -1) { // 设置flags
perror("fcntl - SETFL");
exit(EXIT_FAILURE);
}
}
设置阻塞模式
void setStdinBlocking(void) {
int flags = fcntl(STDIN_FILENO, F_GETFL, 0); // 获取当前flags
if (flags == -1) {
perror("fcntl - GETFL");
exit(EXIT_FAILURE);
}
flags &= ~O_NONBLOCK; // 移除非阻塞标志
if (fcntl(STDIN_FILENO, F_SETFL, flags) == -1) { // 设置flags
perror("fcntl - SETFL");
exit(EXIT_FAILURE);
}
}
这两个函数通过修改stdin的文件描述符的标志来实现将stdin设置为非阻塞模式和阻塞模式。fcntl
系统调用通过提供F_SETFL
命令来设置文件状态标志,其中O_NONBLOCK
表示非阻塞模式。fcntl
的F_GETFL
命令用于获取当前的文件状态标志。
这些改变仅对当前进程有效,因为它们是通过改变进程内部的文件描述符来实现的。一旦进程终止,这些更改不会影响到其他进程或系统级别的设置。