My friend has an below assignment , can anyone can guide how to do this in "C", just guidence is enough.
Write a program to store all processes list into a file and sort all the processes with UID.
For example:
./a.out processidlist.txt
it has to save the info to processidlist.txt.
In this processidlist.txt it has to sort the processes with UID.
he tried the below
ps –A –o UID > outputfile
Thanks
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp1, *fp2;
FILE *fp;
int status;
char path[1035];
fp1 = fopen( argv[1], "w" );
if ( ! fp1 )
{
printf("Error opening file %s\n", argv[1]);
}
/* Open the command for reading. */
fp = popen("ps -Af | sort -k1", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit;
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path)-1, fp) != NULL) {
printf("%s", path);
fputs( path, fp1 );
}
/* close */
pclose(fp);
fclose(fp1);
return 0;
}