C code to read a /proc file in Linux user-space - Live Demo and ExampleC code to read a /proc file in Linux user-space - Live Demo and Example

/proc files are unique they are Kernel generated files (and filesystem). Hence unlike the files situated on a disk which are read and served whenever we access them, /proc files are directly rendered/generated by Kernel when we access. Hence they are supported via its backing driver code. /proc is one of the most popular kernel to user-space interface which you can leverage to add an interface to your Kernel code such as Kernel modules, Kernel Device Drivers, etc. If you are interested sample Kernel create and read /proc file kindly click HERE for more details.

Hence to read such /proc files in C, it is not easy and straightforward. Since these files are zero byte sized files. This again indicates these are generated on the fly. And they don’t come out of storage device (either disk or RAM). So here is my Youtube video with a live demo and example C code to read a /proc file in Linux user-space.

Here is my sample source-code discussed in the video:

/* The Linux Channel
 * Code for Video Episode: 345 C-code to read a proc file in Linux user-space - Live Demo and Example
 * Author: Kiran Kankipati
 * Updated: 10-Jun-2018
 */

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

FILE *fp;

#define MAXBUFLEN 1000000 
unsigned char buf[MAXBUFLEN]; int buflen=0;


void main(void)
{   int i=0;
	 buflen=0;
	 fp = fopen("/proc/cpuinfo", "rb"); if(fp!=NULL) { while(!feof(fp)) { buflen = fread(buf, 1, MAXBUFLEN, fp); } fclose(fp); }


	 if(buflen>1) 
	 {	//raw (hex) dump
	 	for(i=0;i<buflen;i++) { printf("%02x ", buf[i]); if(i%8==0) { printf(" "); } if(i%16==0) { printf("\n"); } } printf("\n");
	 	
	 	//string (readable characters) dump
	 	//for(i=0;i<buflen;i++) { printf("%c", buf[i]); } printf("\n");
	 }

}