Output / input stream of external program

Hi!
I want to build a software that's able to start a certain process.
The software must be able to get every output of this process and send input to this process somehow. (The process sends std::cout 's and wants some std::cin 's)

Is there any way to handle this task?
That's pretty standard on Unix, there are lots of examples available. What platform are you using?
I'm using Ubuntu / Debian. But I haven't found anything useful until now, because what I know system(); couldn't handle this task, because it returns the integer of the main function. If completed.
Last edited on
I found something working in C, but is there a better way using STL of C++ than this one:

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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(){

	pid_t pid;
	int rv;
	int	commpipe[2];		/* This holds the fd for the input & output of the pipe */

	/* Setup communication pipeline first */
	if(pipe(commpipe)){
		fprintf(stderr,"Pipe error!\n");
		exit(1);
	}

	/* Attempt to fork and check for errors */
	if( (pid=fork()) == -1){
		fprintf(stderr,"Fork error. Exiting.\n");  /* something went wrong */
		exit(1);        
	}

	if(pid){
		/* A positive (non-negative) PID indicates the parent process */
		dup2(commpipe[1],1);	/* Replace stdout with out side of the pipe */
		close(commpipe[0]);		/* Close unused side of pipe (in side) */
		setvbuf(stdout,(char*)NULL,_IONBF,0);	/* Set non-buffered output on stdout */
		sleep(2);
		printf("Hello\n");
		sleep(2);
		printf("Goodbye\n");
		sleep(2);
		printf("exit\n");
		wait(&rv);				/* Wait for child process to end */
		fprintf(stderr,"Child exited with a %d value\n",rv);
	}
	else{
		/* A zero PID indicates that this is the child process */
		dup2(commpipe[0],0);	/* Replace stdin with the in side of the pipe */
		close(commpipe[1]);		/* Close unused side of pipe (out side) */
		/* Replace the child fork with a new process */
		if(execl("child","child",NULL) == -1){
			fprintf(stderr,"execl Error!");
			exit(1);
		}
	}
	return 0;
}
i found a silly way, run this command:
system("app > resault.txt")
then u need to read resault.txt from the parent app.
I think that's a good example.

STL can't really help with the actual pipe management. GCC used to have a vendor specific extension to the IO Stream library that allowed you to construct an fstream from a file descriptor, but that's not standard so I'd avoid it.
There is boost, however. Look for file descriptor.

By the way, use perror when system calls fail. It reads errno, so you get a message of what went wrong
Topic archived. No new replies allowed.