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?

2
  • maybe you are searching for something like PIPE? Commented Jul 9, 2012 at 14:21
  • Consider adding the C tag since you asked about C. Commented Jul 9, 2012 at 14:25

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.