/* procfs.c */ /* Read in proc file system data for PID given on command line */ #define _STRUCTURED_PROC 1 /* THIS IS IMPORTANT */ #include #include #include #include #include #include #include #include psinfo_t info; prusage_t usage; int main( int argc, char **argv) { char name[30]; char base[30]; int fd; int len; /* Ensure that user provided a command line parameter */ if (argc < 2) { printf("Usage is a.out pid \n"); printf("Goodbye \n"); exit(1); } /* If user supplied 123 as a pid, we construct the string */ /* /proc/123 here */ strcpy(base, "/proc/"); strcat(base, argv[1]); /* Copy /proc/123 to name and then create /proc/123/psinfo */ strcpy(name, base); strcat(name, "/psinfo"); /* Attempt to open the file */ fd = open(name, O_RDONLY); if (fd < 0) { printf("Attempt to open %s failed \n", name); exit(1); } /* Read data into the structure that maps it and verify length read */ len = read(fd, &info, sizeof(info)); if (len != sizeof(info)) { printf("Length error expected %d got %d \n", sizeof(info), len); } close(fd); /* Print required fields... The only way to know the names of the */ /* required structure elements is to READ /usr/include/sys/procfs.h */ printf("Program name is: %12s \n", info.pr_fname); /* Repeat the process for the usage structure */ strcpy(name, base); strcat(name, "/usage"); fd = open(name, O_RDONLY); len = read(fd, &usage, sizeof(usage)); if (len != sizeof(usage)) { printf("Length error expected %d got %d \n", sizeof(usage), len); } close(fd); printf("User CPU time: %12d.%03d \n", usage.pr_utime.tv_sec, usage.pr_utime.tv_nsec / 1000000); }