其实对于一般的波特率glibc里面已经封装了函数接口,而且非常容易的就可以设置。
但是对于非标准的波特率网上有人提到了ioctl设置,但是最新的内核已经弃用了这种方式,我设置的时候ioctl返回无效
http://blog.chinaunix.net/uid-9543173-id-1988980
我们的方法贴出来:
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#include <linux/termios.h>
int ioctl(int d, int request, ...);
int main(int argc, char *argv[])
{
struct termios2 t;
int fd,baud;
if (argc != 3)
{
fprintf(stderr,"usage: %s <device> <baud>\n", argv[0]);
return 1;
}
fd = open(argv[1], O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1)
{
fprintf(stderr, "error opening %s: %s", argv[1], strerror(errno));
return 2;
}
baud = atoi(argv[2]);
if (ioctl(fd, TCGETS2, &t))
{
perror("TCGETS2");
return 3;
}
t.c_cflag &= ~CBAUD;
t.c_cflag |= BOTHER;
t.c_ispeed = baud;
t.c_ospeed = baud;
if (ioctl(fd, TCSETS2, &t))
{
perror("TCSETS2");
return 4;
}
if (ioctl(fd, TCGETS2, &t))
{
perror("TCGETS2");
return 5;
}
printf("actual speed reported %d\n", t.c_ospeed);
return 0;
}
其实看到我们用的结构体是 struct termios2 ,特别说明,这个结构体有别于 struct termios,以前内核使用 struct termios,glibc里面也使用该结构体,但是内核更新了 struct termios2,glibc到目前为止没有更新。
当然遗憾的是这个好像只实现了波特率,其他的什么停止位什么的我们依旧用以前的,但是发现编译的时候glibc的头文件和我们引用的内核头文件冲突,https://stackoverflow.com/questions/37710525/including-termios-h-and-asm-termios-h-in-the-same-project 非常easy,解决