#include <stdio.h>
#include <unistd.h>
int main ()
{
Char castdoutline[1024]; One line of information in the standard output of the PS command
char* pctmp = NULL; A string that points to a space split
Char caselfpid[10]; PID String for self process
Char 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 for easy control of branch level, easy to control branch flow
{
By creating a pipe, call fork to produce a child process,
Executes 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 using 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))
{
and split the string with the space separator
Pctmp = Strtok (Castdoutline, "");
User name skipped, match PID directly, do not match skip
Pctmp = Strtok (NULL, "");
if (0!= strncasecmp (caselfpid,
Pctmp,
Strlen (Caselfpid))
{
Continue
}
read out process itself CPU occupancy rate
Pctmp = Strtok (NULL, "");
printf ("CPU =%s%%\n", pctmp);
read out the process's own MEM occupancy rate
Pctmp = Strtok (NULL, "");
printf ("MEM =%s%%\n", pctmp);
Break
}
Close the standard I/O stream, wait for the command to finish, and then return to the shell's termination state.
If the shell cannot be executed,
Then the Pclose () returns the same termination status as the shell has executed exit.
Pclose (FP);
}while (0);
}