1

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?

Aymanadou
  • 1,170
  • 1
  • 14
  • 32

5 Answers5

2

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

Šimon Tóth
  • 33,420
  • 18
  • 94
  • 135
2

Sounds like you're afraid to use libraries. Please try and use libraries, they're just as much part of Unix as shell tools.

buddhabrot
  • 1,518
  • 9
  • 14
2

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);
pmg
  • 98,431
  • 10
  • 118
  • 189
1

You should open a pipe using popen but this sounds tedious. A C program calling a shell script for a password.

Noufal Ibrahim
  • 66,768
  • 11
  • 123
  • 160
1

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.

Community
  • 1
  • 1
Patryk
  • 1,341
  • 7
  • 20