I have C program ( program.c ) that calls a shell script ( command.sh ).
command.sh returns an output (a password), i need to get this output in my program.c.
using system(command);
, i can't get hold of the output.
is there any other way in C to solve my problem?

- 1,200
- 1
- 14
- 36
-
Are you required to use `system()` (is this homework)? – pilcrow Dec 09 '11 at 13:25
-
@pilcrow i search for another way ,if exist. (this is not a homework;)) – Aymanadou Dec 09 '11 at 13:33
-
See this post: http://stackoverflow.com/questions/646241/c-run-a-system-command-and-get-output/646254#646254 – Deqing Dec 22 '11 at 06:55
5 Answers
Not in pure C. You want POSIX. Specifically popen
function.
The specification has a nice example, that you can just copy 1:1 http://pubs.opengroup.org/onlinepubs/009604499/functions/popen.html

- 35,456
- 20
- 106
- 151
-
I hoped for a mechanism that uses the memory as intermediate between my program c and the script shell.I won't use files. Thank you – Aymanadou Dec 09 '11 at 13:28
-
1@Aymanadou Well yes, this solution is using a PIPE, that's just a buffer. – Šimon Tóth Dec 09 '11 at 13:31
Sounds like you're afraid to use libraries. Please try and use libraries, they're just as much part of Unix as shell tools.

- 1,558
- 9
- 14
In pure C (well ... ignoring the contents of the system()
call) you can redirect the shell script output to a file, then read that file.
system("whatever > file");
handle = fopen("file", "r");
/* if ok use handle */
fclose(handle);

- 106,608
- 13
- 126
- 198
You should open a pipe using popen
but this sounds tedious. A C program calling a shell script for a password.

- 71,383
- 13
- 135
- 169
You can use popen()
as suggested above, but note that in this case you have no control over the process you created (e.g. you will not be able to kill it), you also will not know its exit status.
I suggest using classical pipe/fork/exec combination. Then you will know the pid of your child process, so you will be able so send signals, also with pipe()
you are able to redirect process standard output, so you can easily read it in your parent process. As example you can see my accepted answer to popen() alternative.