Find the answer to your Linux question:
Results 1 to 3 of 3
Hi, I am having problems executing the shell commands in C. I want to execute a shell command in C then capture the output of shell command and process the ...
  1. #1
    Just Joined!
    Join Date
    May 2011
    Posts
    3

    How to execute shell command in C?

    Hi,

    I am having problems executing the shell commands in C. I want to execute a shell command in C then capture the output of shell command and process the output further. I used following code to perform the functionality. But, the issue is when the shell command won't return any output, fgets() returns junk information?

    To explain with an example, if /etc/version contains ',' seperated values, shell returns the output and fgets returns the value returned by shell command, but when /etc/version doesn't contian any ',' seperated values, shell doesn't return any value and fgets returns junk information. Is there any workaround for this issue or is there any alternative solution to execute shell command in C and capture shell command output?


    char return_val[256];
    FILE *fp = NULL;
    char line[256];
    memset (return_val, 0, 256);
    /* set the defalut value */
    strncpy (return_val, "N/A", 4);
    char cmd[] = "if [ -f /etc/umts2100_version ]; then cut -d, -f1 -s /etc/umts2100_version ; fi";

    /* Open the command for reading. */
    fp = popen(cmd, "r");
    if (fp != NULL)
    {
    /* read the line from file */
    fgets (line, 256, fp);
    if( line != NULL)
    {
    /* copy the data */
    strncpy(return_val, line, strnlen (line, 256));
    }
    /* close the file */
    pclose (fp);
    }

  2. #2
    Linux User
    Join Date
    Jan 2005
    Location
    Saint Paul, MN
    Posts
    260
    your problem is then when the file does not exist, your shell script does output anything.
    See the changed line of code for:
    Code:
    char cmd[] = "if [ -f /etc/umts2100_version ]; then cut -d, -f1 -s /etc/umts2100_version ; fi";
    In the following...
    Code:
    char return_val[256];
    FILE *fp = NULL;
    char line[256];
    memset (return_val, 0, 256);
    /* set the defalut value */
    strncpy (return_val, "N/A", 4);
    char cmd[] = "if [ -f /etc/umts2100_version ]; then cut -d, -f1 -s /etc/umts2100_version ; else echo ; fi";
    
    /* Open the command for reading. */
    fp = popen(cmd, "r"); 
    if (fp != NULL)
    {
        /* read the line from file */
        fgets (line, 256, fp);
        if( line != NULL)
        {
            /* copy the data */
            strncpy(return_val, line, strnlen (line, 256));
        }
        /* close the file */
        pclose (fp);
    }

  3. #3
    Just Joined!
    Join Date
    May 2011
    Posts
    3

    Thumbs up

    Thanks for the reply

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •