#include <stdio.h> #include <unistd.h> int main (){Char castdoutline[1024];//A line of information in the standard output of the PS commandchar* pctmp = NULL; Points to a string after splitting with a space Char caselfpid[10]; Self-process PID stringChar capscmd[24]; "PS aux | grep PID "command string memset (caselfpid, 0, sizeof (caselfpid));sprintf (Caselfpid,"%d",getpid ()); memset (capscmd, 0, sizeof (capscmd));sprintf (Capscmd,"PS aux | grep%d ",getpid ()); Do //non-loop, just to facilitate control of branch level, easy to control branch flow {//By creating a pipeline, call fork to produce a child process,//execute a Shell to run a command to open a process. //This process must be closed by the Pclose () function. file* fp = Popen (Capscmd,//A pointer to a NULL-terminated shell command string,//This line of command will be uploaded to Bin/sh and use the-C flag,//Then the shell will execute this command to read from this string. "R"); Standard output of a file pointer connected to a shell command if (NULL = = fp) {printf ("Call Popen is failed\n");Break ; } memset (castdoutline, 0, sizeof (castdoutline));while (NULL! = fgets (Castdoutline,sizeof (castdoutline),FP)) {//split string with space separatorpctmp = strtok (Castdoutline, ""); //user name skipped, direct matching PID, mismatched skippctmp = strtok (NULL, "");if (0! = strncasecmp (Caselfpid,Pctmp,strlen (caselfpid))) {continue; } //read out process itself CPU usagepctmp = strtok (NULL, "");printf ("CPU =%s%%\n", pctmp); //read out process self MEM occupancy ratepctmp = strtok (NULL, "");printf ("MEM =%s%%\n", pctmp); Break ; } //Close the standard I/O stream, wait for the command to finish, and return to the Shell's terminating state. //If the shell cannot be executed,//The terminating state returned by Pclose () is the same as the shell has executed exit. Pclose (FP); }while (0);} $ gcc main.c-o test$./testCPU = 1.0%MEM = 0.0
$ ps auxuser PID%cpu%MEM VSZ RSS TTY STAT START time COMMANDNSC 24505 1.0 0.0 2004 232 pts /0 s+ 09:46 0:00./test Turn from: http://blog.sina.com.cn/s/blog_4c451e0e0101cmrq.html
Using pipelines to perform PS aux under Linux | grep process ID to get CPU and memory usage