9

Filter the output of a command

  1. /*
  2.  * Runs ps -e and lists processes matching argument.
  3.  *
  4.  *   popen
  5.  *   pclose
  6.  *   strstr
  7.  */
  8.  
  9. #include <stdio.h>
  10. #include <stdlib.h>
  11. #include <errno.h>
  12. #if defined( LINUX )
  13. #include <string.h>
  14. #endif
  15.  
  16. #define PS          "/bin/ps -e"
  17.  
  18. int main( int argc, char *argv[] ) {
  19.     FILE *pfd;
  20.     char *proc;
  21.  
  22.     char line[4096];
  23.  
  24.     switch ( argc ) {
  25.     case 2:
  26.         proc = argv[1];
  27.         break;
  28.     default:
  29.         usage: fprintf( stderr, "%s procname\n", argv[0] );
  30.         exit( 1 );
  31.     }
  32.  
  33.     if ( (pfd = popen( PS, "r" )) == NULL ) {
  34.         fprintf( stderr, "%s\n", strerror( errno ) );
  35.         exit( 1 );
  36.     }
  37.  
  38.     while ( fgets( line, sizeof(line), pfd ) != NULL )
  39.         if ( strstr( line, proc ) )
  40.             fputs( line, stdout );
  41.  
  42.     pclose( pfd );
  43.  
  44.     exit( 0 );
  45. }

Comments

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].