/* Christopher Huyler */
/* short.c */
/* Solution for Project 1 Part C
   - Print CPU time for users/system/idle
   		open stat and find the line begining with cpu
   		then store the four numbers in the line
   - Print the number of disk requests made
   		find the line begining with disk then
   		store the number in that line
   - Print the number of context switches performed
   - Print the time when the CPU was last booted
   		find the line begining with btime and
   		store the number. use functions in time.h
   		to convert seconds since 1970 to a date
   - Print the number of processes created */


#include <stdio.h>
#include <string.h>
#include <sys/time.h>

#define MAX_LEN 80

void printShort()
{
	FILE *fp;					/* file pointer */
	char lineBuf[MAX_LEN],      /* char array line buffer */
		 junk[16];              /* junk char array */
	int usr1,					/* time cpu spent in user mode */
		usr2,                   /* time cpu spent in special user mode */
		sys,                    /* system mode */
		idle,                   /* idle */
		disk,                   /* number of disk requests made */
		ctxt,                   /* number of context switches performed */
		btime,                  /* boot time */
		procs;                  /* number of processes */

		struct timeval boot;	/* formatted boot time */

/* print CPU time (user/system/idle) */
	if ((fp = fopen("/proc/stat","r")) == NULL)
	{
		printf("read: can't open file\n");
		exit(1);
	}
	else
	{/* read cpu line and print times */
		fgets(lineBuf,MAX_LEN,fp);
		while(strncmp("cpu",lineBuf,3) != 0)
			fgets(lineBuf,MAX_LEN,fp);
		sscanf(lineBuf,"%s%d%d%d%d",junk,&usr1,&usr2,&sys,&idle);
		printf("Distribution(s)\t: %d:%d:%d",usr1+usr2,sys,idle);
		printf("\t(user/system/idle)\n");

/* print disk requests made on system (same file)*/
		fgets(lineBuf,MAX_LEN,fp);
		while(strncmp("disk",lineBuf,4) != 0)
			fgets(lineBuf,MAX_LEN,fp);
		sscanf(lineBuf,"%s%d",junk,&disk);
		printf("Disk Requests\t: %d\n",disk);

/* print context switches performed (same file) */
		fgets(lineBuf,MAX_LEN,fp);
		while(strncmp("ctxt",lineBuf,4) != 0)
			fgets(lineBuf,MAX_LEN,fp);
		sscanf(lineBuf,"%s%d",junk,&ctxt);
		printf("Context Switches: %d\n",ctxt);

/* print the time the system was last booted (same file) */
		fgets(lineBuf,MAX_LEN,fp);
		while(strncmp("btime",lineBuf,5) != 0)
			fgets(lineBuf,MAX_LEN,fp);
		sscanf(lineBuf,"%s%d",junk,&btime);
		boot.tv_sec = btime;
		printf("Boot Time\t: %s",ctime(&(boot.tv_sec)));

/* print the number of processes that have been created */
		fgets(lineBuf,MAX_LEN,fp);
		while(strncmp("processes",lineBuf,9) != 0)
			fgets(lineBuf,MAX_LEN,fp);
		sscanf(lineBuf,"%s%d",junk, &procs);
		printf("Processes\t: %d\n",procs);

		fclose(fp);			/* close file */
	}
}



