Use file locks to synchronize stdout instead of a pthread mutex

This commit is contained in:
Cameron Gutman 2015-12-21 15:07:37 -08:00
parent 7d2647f830
commit 394221f3df

View File

@ -30,7 +30,6 @@ struct DeviceEntry {
static struct DeviceEntry *DeviceListHead; static struct DeviceEntry *DeviceListHead;
static int grabbing = 1; static int grabbing = 1;
static pthread_mutex_t DeviceListLock = PTHREAD_MUTEX_INITIALIZER; static pthread_mutex_t DeviceListLock = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t StdoutLock = PTHREAD_MUTEX_INITIALIZER;
// This is a small executable that runs in a root shell. It reads input // This is a small executable that runs in a root shell. It reads input
// devices and writes the evdev output packets to stdout. This allows // devices and writes the evdev output packets to stdout. This allows
@ -57,13 +56,13 @@ static int hasKey(int fd, short key) {
} }
static void outputEvdevData(char *data, int dataSize) { static void outputEvdevData(char *data, int dataSize) {
// We need to hold our StdoutLock to avoid garbling // We need to lock stdout before writing to prevent
// input data when multiple threads try to write at once. // interleaving of data between threads.
pthread_mutex_lock(&StdoutLock); flockfile(stdout);
fwrite(&dataSize, sizeof(dataSize), 1, stdout); fwrite(&dataSize, sizeof(dataSize), 1, stdout);
fwrite(data, dataSize, 1, stdout); fwrite(data, dataSize, 1, stdout);
fflush(stdout); fflush(stdout);
pthread_mutex_unlock(&StdoutLock); funlockfile(stdout);
} }
void* pollThreadFunc(void* context) { void* pollThreadFunc(void* context) {