示例:

假定我们要从一个串口和一个 socket 读取数据.需要判断每个文件描述符的输入数据情况,但 10 妙内无数据的话,需要通知用户没有数据可读.

/* Initialize the input set */

FD_ZERO(input);

FD_SET(fd, input); FD_SET(socket, input);

max_fd = (socket > fd ? socket : fd) + 1;

/* Initialize the timeout structure */

timeout.tv_sec  = 10; timeout.tv_usec = 0;

/* Do the select */

n = select(max_fd,NULL, NULL, ;

/* See if there was an error */

if (n 0)

perror("select failed");

else if (n == 0)

puts("TIMEOUT");

else

{

/* We have input */

if (FD_ISSET(fd, input))

process_fd();

if (FD_ISSET(socket, input))

process_socket();

}

三.unix/linux下,采用 ioctl函数来实现串口配置功能int ioctl(int fd, int request, ...); fd 是串口描述符,request参数是定义在的常量,一般是下表中的一个

Table 10 - IOCTL Requests for Serial Ports

Request Description POSIX Function

TCGETS

Gets the current serial

port settings.

tcgetattr

TCSETS

Sets the serial port

settings immediately. tcsetattr(fd, TCSANOW, &options)

TCSETSF

Sets the serial port

settings after flushing the

input and output buffers. tcsetattr(fd, TCSAFLUSH, &options)

TCSETSW

Sets the serial port

settings after allowing

the input and output

buffers to drain/empty. tcsetattr(fd, TCSADRAIN, &options)

TCSBRK

Sends a break for the

given time. tcsendbreak, tcdrain

TCXONC

Controls software flow

control.

tcflow

TCFLSH

Flushes the input and/or

output queue.

tcflush

TIOCMGET

Returns the state of the

"MODEM" bits.

None

TIOCMSET

Sets the state of the

"MODEM" bits.

None

FIONREAD

Returns the number of

bytes in the input buffer.

None

为获取状态位,调用 ioctl函数,用一个整数来存放位指针.

Listing 5 - Getting the MODEM status bits. #include #include

int fd;

int status;

ioctl(fd, TIOCMGET, &status);

Listing 6 - Dropping DTR with the TIOCMSET ioctl. #include #include

int fd;

int status;

ioctl(fd, TIOCMGET, &status);

status &= ~TIOCM_DTR;

ioctl(fd, TIOCMSET, status);


相关内容