-1

I am trying to return the value of a shell script. From what I have read it looks like i can use popen, but for some reason I can not get the code to work. Right now when I run the code I get garbage characters and not the float I am wanting.

The value form the shell script is a float.

I want to return the value of a bash script so I can use the returned value from the shell scrip as variables for my C code.

#include <stdio.h>

//Settings Variables
 float upload_speed;
 float download_speed;

int main(int argc, char **argv)
{

    FILE *upload_speed;

    //Runs shell script on code and returns data
    upload_speed = popen("./Filter_Data.sh Upload", "r");
    printf("return value is: %s", upload_speed);
    return 0;
}
24
  • 1
    Please post a minimal reproducible example, including what you expected to happen and what actually happened instead. Commented Sep 12, 2018 at 18:41
  • @melpomene That is the code so far for the C part. Commented Sep 12, 2018 at 18:46
  • 1
    Why are you including <mysql/mysql.h>? Why do you have global variables (that are unused)? Have you ever done anything with files in C (e.g. using fopen, fread, fgets, etc)? Commented Sep 12, 2018 at 18:48
  • 1
    What compiler options are you using? If you're using gcc, you should at minimum have gcc -Wall -Wextra -pedantic -O2. Commented Sep 12, 2018 at 18:49
  • @melpomene, that was later on in the code, the value way going to be added to a table. I omitted that code for now. I am using geany, and my code complies fine. Commented Sep 12, 2018 at 18:55

1 Answer 1

3

The popen function returns a pointer to a FILE object representing the input and output of the executed program. You're treating it as a string (i.e. a char *) which it is not.

You need to read from the file object to get its output:

FILE *outputFile;
char outputStr[80];

outputFile = popen("./Filter_Data.sh Upload", "r");
if (outputFile) {
  fgets(outputStr, sizeof(outputStr), outputFile);
  printf("output is: %s", outputStr);
  pclose(outputFile);
}
Sign up to request clarification or add additional context in comments.

9 Comments

I see it returns the first line, is there a way to get it to return the last night result of the shell script? And thank you
Need to use pclose(), not fclose().
@Vlad Knowing what the script outputs, you would need to read multiple lines and parse them to get the information you want.
@Shawn Good catch. Fixed.
@dbush and how would I parse them? Sorry, in all of the time i worked with C I never really interacted with fgets
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.