I have some code working using libusb. The code detects a USB device attach/detach event. When attached my code will make a folder /media/usb_device then mount my USB to this folder. For each command I use popen. My issue is I have to use a sleep command between the mkdir and mount commands.
Is there a way to make this more clean? Avoid the seemingly random sleep?
Second, how can I capture the popen output? A different stack overflow question showed the method I am using. No luck.
#define BUFFER_SIZE 100
static bool run_command(char* cmd) {
sleep(2);
bool cmd_success = false;
char result[BUFFER_SIZE];
memset(&result, 0, BUFFER_SIZE);
FILE *f = popen(cmd, "r");
if(f == NULL) {
syslog(LOG_ERR, "Error running command %s\n", cmd);
}
else {
while(fgets(result, sizeof(result), f) != NULL) {
printf("%s", result);
}
cmd_success = true;
}
pclose(f);
return cmd_success;
}
void config_file_handler_init(void) {
bool mkdir = run_command("mkdir /media/usb_device");
bool mount = run_command("mount /dev/sda1 /media/usb_device");
if(mkdir && mount) {
printf("We found a USB and mounted it. Now we can look through the files and act!\n");
}
}