0

I want to get return value from my script using c code. Consider my script is in another partition, I am mounting that partition and i am calling like,

value=system("./mnt1/myscript.img");

I need one function in myscript.img file and that should return one value (ex: mmcpart) How can i frame the script to get return value. can anyone help me to solve this issue. Thanks in advance.

DYZ
  • 55,249
  • 10
  • 64
  • 93

2 Answers2

1

You can write the output of the shell script in a file and read the file content from the C program.

Your C program must attempt to read the file only when the shell script process is complted, preferably with $? = 0.

You can put the name of your shell script file in .profile file and it will automatically execute your shell script.

Shell script programming possesses powerful file handling commands writing to files should not be an issue.

Not sure why **tee ** command is used. Do you want the output to be sent t STDOUT as well?

subir
  • 310
  • 4
  • 13
  • Thanks ... I think this will help , I will try and let me know..... – Karthikeyan Raju Mar 01 '17 at 04:10
  • How to open a file.... I am running my script in boot time... I tried the following things , (1) cat > filename <<- "EOF" echo "${mmcpart}" | tee info.txt echo "${root_fs}" | tee -a info.txt EOF (2) echo "${mmcpart}" | tee info.txt echo "${root_fs}" | tee -a info.txt Its not working.......... – Karthikeyan Raju Mar 01 '17 at 05:06
  • You can put the name of your shell script file in .profile file and it will automatically execute your shell script. – subir Mar 01 '17 at 08:35
0

What you really need is a pipe and then fork and execvp where you can execute your script. Something like this should work for you

    int mypipe[2];
    if(pipe(mypipe) == -1) {
      perror("Pipe creation failed");
      exit(1);
    }

    if(fork() == 0)            //first fork
    {
        close(STDOUT_FILENO);  //closing stdout
        dup(mypipe[1]);         //replacing stdout with pipe write
        close(mypipe[0]);       //closing pipe read
        close(mypipe[1]);

        const char* myprog[] = { "ps", "-ef", 0};
        execvp(myprog[0], myprog);
        perror("error in execvp for ps command");
        exit(1);
    }

    char str[200];
    FILE* fp = fdopen(mypipe[0], "r");

    while (fgets(str, 200, fp) != 0) {
            printf("%s\n", str);
    }
Aniruddh Dikhit
  • 662
  • 4
  • 10
  • 1
    this answer fails to account for when the call to `fork()` fails. Rather, it assumes the call was successful. – user3629249 Mar 01 '17 at 05:47