Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I run a program from another program and pass data to it via stdin in c or c++?

Tags:

c++

c

stdin

ipc

Say I have an .exe, lets say sum.exe. Now say the code for sum.exe is

void main ()
{
 int a,b;
 scanf ("%d%d", &a, &b);
 printf ("%d", a+b);
}

I wanted to know how I could run this program from another c/c++ program and pass input via stdin like they do in online compiler sites like ideone where I type the code in and provide the stdin data in a textbox and that data is accepted by the program using scanf or cin. Also, I wanted to know if there was any way to read the output of this program from the original program that started it.

like image 807
Shehzan Avatar asked Jan 20 '14 10:01

Shehzan


1 Answers

In C on platforms whose name end with X (i.e. not Windows), the key components are:

  1. pipe - Returns a pair of file descriptors, so that what's written to one can be read from the other.

  2. fork - Forks the process to two, both keep running the same code.

  3. dup2 - Renumbers file descriptors. With this, you can take one end of a pipe and turn it into stdin or stdout.

  4. exec - Stop running the current program, start running another, in the same process.

Combine them all, and you can get what you asked for.

like image 148
ugoren Avatar answered Oct 31 '22 03:10

ugoren