// For debugging #include #include #include #include #include #include /* Remember to free the returned pointer */ char* getoutput(char *command){ size_t space = 16; char *output = malloc(space); int pipe_ends[2]; // pipefd[0] is the read end, pipefd[1] is the write end pipe(pipe_ends); pid_t pid = fork(); if(pid) { // We're the parent close(pipe_ends[1]); size_t position = 0; ssize_t readlen; while((readlen = read(pipe_ends[0], output + position, 16)) > 0 ){ position += readlen; output = realloc(output, space + 16); space += 16; } output[position] = 0; wait(NULL); return output; } else { // We're the child dup2(pipe_ends[1], 1); execl("/bin/sh", "sh", "-c", command, NULL); printf("This won't happen\n"); exit(1); } } /* Note: This command is specific to the formatting dmesg uses */ char *get_owl_usb(){ char *ousb = getoutput("dmesg | grep 'Product: Meeting Owl' | cut -d : -f 1 | cut -d ']' -f 2 | cut -d ' ' -f 3 | tail -n 1"); ousb[strlen(ousb) - 1] = 0; return ousb; } /* Note: This command assumes that the failure will be in the last 10 lines * It also assumes there was no previous failure within the last 10 lines */ int failed(char *owl_usb){ char command[128]; sprintf(command, "dmesg | tail -n 10 | grep %s | grep -e failed -e disconnect > /dev/null", owl_usb); return !system(command); } #define WORKING 1 #define FAILED 2 int main(){ /* For debugging, comment out this part and printf will still work and so will ctrl+c */ pid_t child_pid = fork(); if(child_pid){ // We're the parent return 0; } //*/ // We're the child int state = WORKING; char *owl_usb = get_owl_usb(); while(1){ if(state == WORKING){ sleep(5); if(failed(owl_usb)){ state = FAILED; system("gedit /home/seth/failed.html"); } } if(state == FAILED){ sleep(60); owl_usb = get_owl_usb(); if(!failed(owl_usb)) state == WORKING; } } return 0; }