Catch stderr and stdout from external program

Hi
I am trying to write a program that runs an external program.
I know that I can catch stdout, and I can catch stdout and stderr together BUT the question is can I catch the stderr and stdout separated?
I mean for example, stderr in varaible STDERR and stdout in variable STDOUT.
Also I need the exit code of the external program.

Thanks a lot.
You can't do it with csh.

Start with this, noise.c:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <stdio.h>

int main()
{
	int i;

	for (i = 0; i < 26; i++)
	{
		fprintf(stdout, "%c\n", 'A' + i);
		fprintf(stderr, "%c\n", 'a' + i);
	}

	return 0;
}


Build it, then run:
 
./noise > out 2> out2
Last edited on
I don't want to write them into Separate Files and then read from File.
I want to catch them directly into my variable.
Like the way we read stdout line by line with file descriptor.
Use fork + execvp. Sketch of solution (not a complete solution - you have to add error checking, includes, declarations):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
int in_pipe[2];
int out_pipe[2];
int err_pipe[2];
  
pipe(in_pipe);
pipe(out_pipe);
pipe(err_pipe);

int pid = fork();
if (pid == 0)
{
   dup2(in_pipe[0], 0);
   dup2(out_pipe[1], 1);
   dup2(err_pipe[1], 2);
   close(in_pipe[0]);
   close(out_pipe[1]);
   close(err_pipe[1]);
   // to be truly correct, you should also close all other inherited descriptors child doesn't need
   
   execvp(program, argv);
   _exit(127);
}

close(in_pipe[0]);
close(out_pipe[1]);
close(err_pipe[1]);

if (pid < 0)
  // failure, close the other ends of pipes
else
  // here you can write to in_pipe[1] and read from out_pipe[0] and err_pipe[0] to communicate with the child process
  // remember to call waitpid when you finish 
Last edited on
Thanks a lot.
Another question!?
How can I catch the exit code of program?? Or the PID of the external program!?
I know I can read $? but is there another way??
Last edited on
Use waitpid. It returns the exit code. Actually you *have* to use it, otherwise the child process becomes a zombie.
or an orphan.
Topic archived. No new replies allowed.