Implement a simple C module to wait for keypresses

This commit is contained in:
Kristóf Tóth 2020-08-17 15:50:39 +02:00
parent 916b3c2836
commit 5c6db0577f
5 changed files with 87 additions and 0 deletions

33
evdev/evdev.c Normal file
View File

@ -0,0 +1,33 @@
#include "evdev.h"
int block_until_keypress(const char* keyboardPath) {
int keyboardFd = open(keyboardPath, O_RDONLY);
if (keyboardFd < 0) {
return keyboardFd;
}
int eventSize = sizeof(struct input_event);
int bytesRead = 0;
struct input_event events[NUM_EVENTS];
int readEvents = 1;
while(readEvents) {
bytesRead = read(keyboardFd, events, eventSize * NUM_EVENTS);
if (bytesRead < 0) {
return bytesRead;
}
for(int i = 0; i < (bytesRead / eventSize); ++i) {
struct input_event event = events[i];
if(event.type == EV_KEY) {
if(event.value == 1) {
readEvents = 0;
}
}
}
}
close(keyboardFd);
return 0;
}

24
evdev/evdev.go Normal file
View File

@ -0,0 +1,24 @@
package evdev
// #cgo CFLAGS: -g -Wall
// #include "evdev.h"
// #include <stdlib.h>
import "C"
import (
"unsafe"
"syscall"
)
func BlockUntilKeypress(devicePath string) error {
path := C.CString(devicePath)
defer C.free(unsafe.Pointer(path))
ret := C.block_until_keypress(path)
if ret < 0 {
return syscall.Errno(ret)
}
return nil
}

14
evdev/evdev.h Normal file
View File

@ -0,0 +1,14 @@
#pragma once
#include <linux/input.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define NUM_EVENTS 128
int block_until_keypress(const char* keyboardPath);

3
go.mod Normal file
View File

@ -0,0 +1,3 @@
module after-lock
go 1.15

13
main.go Normal file
View File

@ -0,0 +1,13 @@
package main
import(
"after-lock/evdev"
"log"
)
func main() {
err := evdev.BlockUntilKeypress("/dev/input/by-id/usb-Dell_Dell_USB_Entry_Keyboard-event-kbd")
if err != nil {
log.Fatal(err)
}
}