请执行我的英语我不是本地人。
Linux 输入设备: /dev/input/event0 或 /dev/input/by-id/usb-Logitech_G29_Driving_Force_Racing_Wheel-event-joystick
问题:我不想读取缓冲数据。
亲爱的 Stackoverflow,
1 - 我在 linux 上打开了一个输入设备。
2 - 我编写了一些代码将设备向左或返回中心。(它是游戏轮,所以当我打开应用程序时,我必须确保轮子位于中心)
3 - 我关闭了文件描述符并打开完全相同的设备以不读取旧的缓冲数据。
4 - 当我想通过读取功能获取数据时,我得到的是当我将设备转到中心时得到的旧缓冲数据。(第一个位置是 0,当我想转动轮子到中心时,它从 0 变为 35000)
那么如何在不编写第二个应用程序的情况下清除缓冲数据呢?因为如果我编写了两个应用程序,第一个应用程序将设备轮设置为中心,第二个应用程序用于获取数据,所以一切都很好。我的意思是,如果我关闭来自不同应用程序的文件描述符,linux 会清除数据,但如果我在同一个应用程序上尝试此操作,则会有缓冲区。
我试图清除缓冲区的内容:
- 首先,我尝试在 google、stackoverflow 上搜索并阅读几乎所有内容。
- 同步()
- fflush(stdin) 和 fflush(stdout)
- ioctl(fd, I_FLUSH, FLUSHRW)
- tcflush(fd, TCIOFLUSH)
- 阅读前关闭(fd)。(我认为这是因为相同的应用程序,linux 给了我相同的文件描述符。如果我退出程序并再次运行所以没有缓冲区)
$ gcc -o test_prog test.c && ./test_prog
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <termios.h>
#include <strings.h>
#include <stropts.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <linux/input.h>
// set the wheel position to center of it
void set_autocenter(int fd, int autocenter) {
struct input_event ie;
ie.type = EV_FF;
ie.code = FF_AUTOCENTER;
ie.value = 0xFFFFUL * autocenter / 100;
if (write(fd, &ie, sizeof(ie)) == -1) {
perror("error set_auto_center");
}
}
int main(int argc, char *argv[]) {
int fd_joystick;
struct input_event ev = {0};
const char *device_wheel = "/dev/input/by-id/usb-Logitech_G29_Driving_Force_Racing_Wheel-event-joystick";
if ((fd_joystick = open(device_wheel, O_RDWR)) < 0) {
perror("device could't opened.");
return 0;
}
set_autocenter(fd_joystick, 100);
while (1) {
/* Problem starts from here
* When I first call read function it gives me garbage data which gets from
* function of set_autocenter. Because this function changes the direction of wheel
*/
if ( read(fd_joystick, &ev, sizeof(struct input_event)) == sizeof(struct input_event)) {
printf("Event Type: %d Event Code: %d Event Value: %d\n", ev.type, ev.code, ev.value);
}
}
return 1;
}
$ cat /proc/bus/输入/设备
I: Bus=0003 Vendor=046d Product=c24f Version=0111
N: Name="Logitech G29 Driving Force Racing Wheel"
P: Phys=usb-0000:00:14.0-11/input0
S: Sysfs=/devices/pci0000:00/0000:00:14.0/usb1/1-11/1-11:1.0/0003:046D:C24F.0040/input/input61
U: Uniq=
H: Handlers=event0 js0
B: PROP=0
B: EV=20001b
B: KEY=1ff 0 0 0 0 0 0 ffff00000000 0 0 0 0
B: ABS=30027
B: MSC=10
B: FF=300040000 0