I am trying to teach myself some redirection. And I have the following problem:
I have a simple program that asks the user for an integer and then outputs some other integers, it does that indefinitely until the user enters 0, then it closes.
I am trying to write a wrapper for that program, in the future it might be some GUI wrapper for another console application. The goal is to communicate with that program.
My first thought was to use pipes, fork the process, set the pipes to the stdin and stdout of the child process and then exec() the console application.
Now, my code so far doesn't work properly, because the console application does get executed but it runs as usual, in the console, the output doesn't go where I want it to go.
main()
{
int master_to_slave[2];
int slave_to_master[2];
pipe(master_to_slave);
pipe(slave_to_master);
int pid;
if((pid=fork())==0){
close(master_to_slave[1]);
close(slave_to_master[0]);
dup2(0, master_to_slave[0]);
dup2(1, slave_to_master[1]);
char *args[] = { NULL };
execv("/home/ebach/Documents/HIWI/random.exe",args);
}
else if(pid<0){
//ALARM ALARM
}
else{
close(master_to_slave[0]);
close(slave_to_master[1]);
while(1){
char buff[16];
int rd = read(slave_to_master[0], &buff, sizeof(buff));
if(rd > 0){
buff[rd-1] = '\0';
printf("Redirected: ");
for(int i = 0; i < rd; i++){
printf("T%c", buff[i]);
}
printf("\n");
}
}
wait(NULL);
}
}
So far it is just supposed to redirect the console app's output. (as you can see it should just add 'Redirected:'
Anyways, I am not entirely proficient in c as you might see, so I can't find the fault.
Did I 'connect' the pipes wrong?
Another solution I came across was the use of pseudo-terminals by using forkpty() and exec(), should I go that route?
Thanks for any help in advance!
You've used dup2
backwards. Per the man page: int dup2(int fildes, int fildes2);
dup2
will cause filedes2
to refer to the same open file as filedes
.