向usb cdrom发送SCSI 命令

1.
#include <stdio.h>
#include <scsi/sg.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdlib.h>
/*****************/
struct  sg_io_hdr * init_io_hdr() 
{
  struct sg_io_hdr * p_scsi_hdr = (struct sg_io_hdr *)malloc(sizeof(struct sg_io_hdr));

  memset(p_scsi_hdr, 0, sizeof(struct sg_io_hdr));
  if (p_scsi_hdr) {
   p_scsi_hdr->interface_id = 'S'; /* this is the only choice we have! */
    /* this would put the LUN to 2nd byte of cdb*/
    p_scsi_hdr->flags = SG_FLAG_LUN_INHIBIT; 
  }
  return p_scsi_hdr;
}
/******************/
void destroy_io_hdr(struct sg_io_hdr * p_hdr) 
{
    if (p_hdr) {
        free(p_hdr);
    }
}
/********************/
void set_xfer_data(struct sg_io_hdr * p_hdr, void * data, unsigned int length) 
{
    if (p_hdr) {
        p_hdr->dxferp = data;
        p_hdr->dxfer_len = length;
    }
}
/********************/
void set_sense_data(struct sg_io_hdr * p_hdr, unsigned char * data,
        unsigned int length) {
    if (p_hdr) {
        p_hdr->sbp = data;
        p_hdr->mx_sb_len = length;
    }
}
/*********************/
int execute_switch(int fd, int mode, struct sg_io_hdr * p_hdr) 
{
    unsigned char cdb[6];
    /* set the cdb format */
    cdb[0] = 0xee; 
    cdb[1] = 0;
    cdb[2] = mode & 0xff;
    cdb[3] = 0;
    cdb[4] = 0;
    cdb[5] = 0;
    
    p_hdr->dxfer_direction = SG_DXFER_NONE;
    p_hdr->cmdp = cdb;
    p_hdr->cmd_len = 6;

    int ret = ioctl(fd, SG_IO, p_hdr);
    if (ret<0) {
        printf("Sending SCSI Command failed.\n");
    }
    return p_hdr->status;
}

/************************main***********************/
int main(int argc,char **argv)
{
	int fd = -1;
	int mode = 0;
	struct sg_io_hdr * p_hdr;
	int i;
	int state =0;

	for(i=0;i<argc;i++){
		printf("argv[%d]:%s\n",i,argv[i]);
	}
	if(argc != 3){
		printf("para error!\n");
		return -1;
	}
	fd = open(argv[1],O_RDWR);
	if(fd <= 0){
		perror("open file error!\n");
		return -1;
	}
	p_hdr = init_io_hdr();
	if(p_hdr == NULL){
		printf("init hdr error!\n");
                return -1;

	}
	mode = atoi(argv[2]);
	printf("mode=%d\n",mode);
	state = execute_switch(fd, mode, p_hdr);
	printf("state:%d\n",state);
	
	destroy_io_hdr(p_hdr);
	close(fd);
	return 0;	
}
2. 使用sg3_utils 工具包


你可能感兴趣的:(向usb cdrom发送SCSI 命令)