Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a bash program accept commands from another C program

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.

like image 672
Karthik Avatar asked Dec 07 '25 23:12

Karthik


2 Answers

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:

  • pipe()
  • fork()
  • dup2()
  • execv()

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).

like image 161
Jonathan Leffler Avatar answered Dec 09 '25 13:12

Jonathan Leffler


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.

like image 44
Leo Izen Avatar answered Dec 09 '25 11:12

Leo Izen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!