Dezhi Zhou
Dezhi Zhou

Reputation: 21

How to pass a value from shell script to C program

I am trying to use system() in C to call shell script to modify a file and execute a executable file and get some output in another directory (not the C working directory). How can I pass the value I got in the shell script to the main C program. Thanks in advance!

#define shell "\
#/bin/bash \n\
cd home/path \n\
"input modification" \n\
./ exe \n\ #output a parameter b in the file out
b=$(cat <out) \n\
echo "b" \n\
"
void main()
{
 system(shell);
 printf("b=d%",b);
}

Upvotes: 1

Views: 694

Answers (1)

Jean-Baptiste Yun&#232;s
Jean-Baptiste Yun&#232;s

Reputation: 36441

First problem:

The best way is to create a temporary file that contains your shell script and execute it. For example you can create it via tmpnam/creat to get a filename, create the file and open it. Then, you have to fill its content with your shell script instructions and use system to execute it after having modify its permissions to execute it (see chmod).

Second problem:

To receive data from a subprocess you need to establish some communication, either by writing/reading in a file, or using a pipe for example. A pipe can be easily established using popen in place of system.

Finally, don't forget to remove every temporary object.

Upvotes: 2

Related Questions