3

I'm new to linux and programming. I opened an application program from a C program using system("Prog");

Prog-> #after opening the program

This "Prog" accepts certain commands from user and displays output.

Prog-> write # Accepts the command from user
1 2 3 4 5    # Displays the output 
Prog->       # Waiting for next command

I want to make the command sent from a C program instead of getting it from the user. I can't use system(""); to send the commands to the opened program "Prog" (as in passing commands to CLI from C program). system(); works only for CLI and not to the opened program.

Is there any way that I can send the commands to opened application from a C program?

I should also store the displayed output "1 2 3 4 5" in a file. Pls help.

Karthik
  • 35
  • 3
  • 2
    It will be easier with `fork` and `execv` than with `system`. Look up the man pages for `fork` and `execv` on the net. – R Sahu Jun 18 '14 at 00:46

3 Answers3

2

Superficially, you might find the popen() function appropriate, along with the pclose() function.

FILE *fp = popen("Prog", "w");

This indicates that your program will write to fp to send data to the standard input of Prog. The standard output of Prog will go to the same place as the standard output of your program. When you're finished, you close the stream with pclose():

pclose(fp);

If you need more control over where the output goes, you will need to use:

If this is insufficient — if Prog does not react well to not having a terminal for input and/or output — then you will need to investigate pseudo-ttys or pty devices. These are a little tricky to use; they're a subject for a separate question (and there's probably several relevant questions with answer already available on SO to cover their use).

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

You can do this by redirecting with fork() and exec(), execv(), execvp(), etc. This creates a separate process, (and this is the standard way to do so, rather than with system), but it allows you to redirect the I/O of that process however you please, similar to how bash does it. Take a look:

http://publicabstractvoid.blogspot.com/2008/01/forkexec-while-redirecting-io.html

Take a look at the dup2(2) and fork(2) manpages.

Leo Izen
  • 4,165
  • 7
  • 37
  • 56
0

If your "Prog" reads the commands from the standard input, you can pipe commands from your C program to "Prog". Also, you can capture, in your C program, the text written by "Prog" to stdout and stderr streams. One example how to do that can be found here: Linux 3.0: Executing child process with piped stdin/stdout

Community
  • 1
  • 1
Oleg
  • 1,037
  • 7
  • 13