Monday, February 25, 2013

User space application to retrieve device file's minor number dynamically

Note: This works only if you have single device node file, working on how to make it work for more than one device file.

Please leave your comments or help me in making it generic :)

I had written an simple linked list device driver code (LKM). I was manually creating a device node/file i.e. "/dev/list0". Since someone asked me to "How to dynamically retrieve minor number" from user space application. Have posted my idea below,

Code snippet:

/* Dynamically getting the device file */
system("ls -als /dev/list* | awk '{print $7}' > device_file.txt");
 
/* Retrieve the device file name from file */
fp = fopen("device_file.txt", "r");
if( fp < 0 )
  fprintf(stdout, "Failed to open the file \n");
else
{   
  fread(&amp, minor, 1, 1, fp);         
  fprintf(stdout, "%d \n", minor);   
  fclose(fp);


/*
 * Minor no read from file would be decimal value
 * i.e. '0' is interpreted as char '0' so decimal value is 48
 * converting it to exact decimal value
 * INFO: atoi() can also be used
*  minor = atoi(minor);
 */
minor = minor - 0x30;
fprintf(stdout, "Final=%d \n", minor);   
snprintf(buf, sizeof("/dev/list0"), "/dev/list%d", minor);

fd = open(buf, O_RDWR);
.....