Thursday, March 11, 2010

Linux - Tips: using bash in Makefile

Object: To change shell to "bash" and use it in make procedure

add this to the top of makefile

SHELL :=/bin/bash

Linux - Unix command in C code

Object: using unix shell command in C and get result from the command.

PS:
1. The sample is type of IPC program, and the command need to go with pipe line( "|" )
2. The sample is referenced from http://www.computing.net/answers/programming/unix-command-in-c/19012.html  nalls's reply

===============================================
complier: gcc command.c  -o command
===============================================
source code:



#include
#include
#include

#define MAX_LINES    256
#define MAX_CHARS    MAX_LINES
#define MAX_TXT        MAX_LINES


/*
 * 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.
 *   
 * URL: http://www.computing.net/answers/programming/unix-command-in-c/19012.html   
 */

/*
 * Fatal Error
 */
int fatal(x)
    char *x;
{
    perror(x);
    exit(1);
}



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
    {
        if(fgets(line, MAX_TXT, ptr) == NULL)
        break;
      
        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*/
           cnt++;
    }
   
      fclose(ptr);
      return cnt;

}





int main()
{
    char *slines[MAX_LINES];
    char sbuf[MAX_CHARS];
    char *com_str="ifconfig | ifconfig eth0 |grep inet";
    int count,i;

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

    if(count == 0)
       exit(1);

    for(i=0; i
       printf("%s\n", slines[i]);
      

    return 0;
}