#include #include #include #include #include #include #include #define CMD_SIZE 6 #define MIN_STRLEN 1 pthread_mutex_t out_mutex = PTHREAD_MUTEX_INITIALIZER; void dump_buf(unsigned char *buf, int len) { int i, nz = 0; for (i = 0; i < len; i++) { if (buf[i]) { nz = 1; break; } } if (!nz) // The buffer is empty. return; pthread_mutex_lock(&out_mutex); for (i = 0; i < len; i++) { if (buf[i]) { int str_len = strlen(&buf[i]); // Short string pieces are too boring. if (str_len >= MIN_STRLEN) { unsigned char *c; for (c = &buf[i]; c < &buf[i + str_len]; c++) { if ((*c > 127) || ((*c < 32) && (*c != 10) && (*c != 13))) { *c = ' '; continue; } } // Dump the buffer. fprintf(stderr, "%s\n", &buf[i]); } i += str_len; } } pthread_mutex_unlock(&out_mutex); } int main(int argc, char *argv[]) { int npages = 128, pages; if (argc > 1) { pages = atoi(argv[1]); if (pages > 0 && pages < 1024) npages = pages; } int buf_size = 4096 * npages; int fd = open("/dev/sg0", O_RDONLY); if (fd == -1) { fprintf(stderr, "open failed!\n"); return 1; } char *out_buf = calloc(1, buf_size); if (!out_buf) { fprintf(stderr, "calloc failed!\n"); return 1; } char cmd[CMD_SIZE] = {}; struct sg_io_hdr hdr; memset(&hdr, 0, sizeof(hdr)); hdr.interface_id = 'S'; hdr.dxfer_direction = SG_DXFER_FROM_DEV; hdr.cmd_len = CMD_SIZE; hdr.dxfer_len = buf_size; hdr.dxferp = out_buf; hdr.cmdp = cmd; int ret = ioctl(fd, SG_IO, &hdr); if (ret == -1) { fprintf(stderr, "ioctl failed!\n"); } dump_buf(out_buf, buf_size); return 0; }