Unix command in C

May 12, 2009 at 04:04:51
Specs: Windows XP
In a C program, I have to continue process based on the output of grep.
If (ps -eaf|grep BD) returns anything (i.e if BD running), I should exit the C application.
How can I achieve this.

See More: Unix command in C

Report •

May 12, 2009 at 11:35:49
If you are using Linux/Unix, one way is use interprocess communication by spawning a shell command from a "C" program by using fopen and then reading the pipe to the end.

I wrote the test program below some years ago. Interprocess and the ps command are tricky so you'll have to test it. On my Solaris 9 box, the count is 2 when nothing is in the process table for a particular grep. Your results may vary:

/* popen() example */
int main()
  char *slines[MAX_LINES];
  char sbuf[MAX_CHARS];
  char *com_str="ps -ef|grep BD";
  int count,i;

  count=run_popen(slines, sbuf, com_str);
  fprintf(stderr,"count is %d\n", count);

  if(count == 0)

  for(i=0; i<count;   i++)
       printf("%s\n", slines[i]);
   * This function executes a piped command passed as
   * a pointer-to-string, exe_str.
   * buffer is the array where each line is stored
   * lineptr is an array-of-pointers where each element of the
   * array points to the beginning of each line stored in buffer.
   * returns the number of lines read into buffer, cnt.
  int run_popen(lineptr, buffer, exe_str)
  char *lineptr[]; /*array-of-pointers to addresses */
  char buffer[];  /*buffer to save strings */
  char *exe_str;   /*pipe command */
  int i, cnt=0;
  FILE *ptr, *popen();
  char *bufstart, *bufend, line[MAX_TXT], *fgets();

  bufstart = buffer;         /*mark start of available space*/
  bufend = buffer + MAX_CHARS;    /*mark end of available space*/
  if((ptr =   popen(exe_str, "r")) == NULL)
       fatal("Couldn't open pipe");

  for(i=0; i<MAX_LINES; i++)
       if(fgets(line, MAX_TXT, ptr) == NULL)
       line[strlen(line)-1] = '\0'; /* no new-lines*/
       if((bufstart + strlen(line) + 1) >= bufend)
          fatal("Line too long");
       lineptr[i]=bufstart;        /*save the address of the line*/
       strcpy(bufstart,line);      /*save the line into buffer*/
       bufstart += strlen(line)+1; /*update starting pointer*/
  return cnt;
   * Fatal Error
  int fatal(x)
  char *x;

Report •
Related Solutions

Ask Question