I'm writing a program in C for Linux. I plan on using popen()
to run another program. While I'm waiting for that program to finish, I want to be able to detect if the user presses keys on the keyboard so I know if they want to continue processing their files or if they want to pause after pclose()
. What is the best way to accomplish this?
CodePudding user response:
You can use two threads, one thread running the popen
commmand while the other thread is waiting for a key, join the first thread and then check if any key was pressed, then pclose
and cancel the thread waiting for a key. An example using C (it is trivial to adapt it to C ), I'm ommiting error checks for brevity:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
FILE *popen(const char *, const char *);
int pclose(FILE *);
static int key;
void *handle_cmd(void *arg)
{
FILE *cmd = arg;
char result[1024];
while (fgets(result, sizeof(result), cmd))
{
printf("%s", result);
}
return NULL;
}
void *handle_key(void *arg)
{
(void)arg;
key = getchar();
return NULL;
}
int main(void)
{
// Simulate a long read using sleep 5
// to give you enough time to press a key enter
FILE *cmd = popen("sleep 5; echo 'command finished'", "r");
pthread_t th_cmd, th_key;
pthread_create(&th_cmd, NULL, handle_cmd, cmd);
pthread_create(&th_key, NULL, handle_key, NULL);
pthread_join(th_cmd, NULL);
if (key != 0)
{
printf("%c was pressed\n", key);
}
pclose(cmd);
pthread_cancel(th_key);
return 0;
}