1

Possible Duplicate:
Best way to capture stdout from a system() command so it can be passed to another function

I have a program in C, in which I invoke a system function, to run a different executable. How do I get the output of the other program on the console, and not on a file. Can something like this be done?

Community
  • 1
  • 1
saurabhsood91
  • 449
  • 1
  • 5
  • 21

3 Answers3

1

Yes. You use pipes. Each process has two standard streams - stdout and stderr. These are just io streams. They could map to files, or to console pipes. When you spawn the new process, you set the new processes output pipes to redirect to file handles on the controlling process. From there you can do whatever you like. You could for example, read the child processes pipes and push their output to the controlling processes output pipes.

In windows you do it like this:

#define SHANDLE         HANDLE

bool CmdShell::makePipe( SHANDLE& read, SHANDLE& write )
{
   SECURITY_ATTRIBUTES sa;
   sa.nLength = sizeof( SECURITY_ATTRIBUTES );
   sa.lpSecurityDescriptor = NULL;
   sa.bInheritHandle = true;

   SHANDLE writeTmp;
   if ( !CreatePipe( &read, &writeTmp, &sa, 0 ))
   {
      assert(0);
      return false;
   }

   if ( !DuplicateHandle( GetCurrentProcess(), writeTmp, 
                          GetCurrentProcess(), &write, 0,
                          FALSE, DUPLICATE_SAME_ACCESS ))
   {
      assert(0);
      return false;
   }
   CloseHandle( writeTmp );

   return true;
}

On linux you do it like this:

#define SHANDLE         int

bool CmdShell::makePipe( SHANDLE& read, SHANDLE& write )
{
   s32 pipeD[2];
   if ( pipe( pipeD ))
   {
      assert(0);
      return false;
   }
   read = pipeD[0];
   write = pipeD[1];
   return true;
}
Rafael Baptista
  • 11,181
  • 5
  • 39
  • 59
0

popen runs another program and gives you a FILE* interface to it's output so you can read it as if you were reading a file, see How to execute a command and get output of command within C++ using POSIX?

Community
  • 1
  • 1
Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
0

The question asked simply, "How do I get the output of the other program on the console..."

The simple answer is for the other program to write to stdout.

The fancier answers are required to pass the output of the 2nd program back to the first.

user15972
  • 124
  • 4