Context: I'm building a UNIX shell, and am currently implementing pipes.
Goal: calls separated by pipes pass output from one to another, only final output is to be printed.
Symptom: the last process continues to output into the pipe, thus I can see nothing and have no clue as to if it executed correctly, received the previous process's output as input etc.
Diagnosing whether I can switch output between the pipe and the console at will: I simply create the pipe, direct it into it and then back to the console, before I proceed to code that precedes the execvp() call (i.e. it should anyway be printed) to see if it's back on the terminal.
Code I tested:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"
#include "errno.h"
#include <sys/wait.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <signal.h>
//all the #includes I've got in the original project
int main(int argc, char* argv[])
{
int fp[2];
pipe(fp);
int saved_fd_0, saved_fd_1;
saved_fd_0 = dup2(fp[0], 0);
saved_fd_1 = dup2(fp[1], 1);
dup2(saved_fd_1, 1);
dup2(saved_fd_0, 0);
close(fp[0]);
close(fp[1]);
printf("output is at terminal");
}
I chose this sequence based on this answer but it fails to print anything past this piece of code. Unfortunately similar questions I have found typically come down to an fflush() call or aren't concerned with restoring output to the terminal (i.e. I didn't just ask without doing any research).
Many thanks in advance.
I am testing with ls | wc
as input.