thanks in advance for any help.
I am trying to replicate the behavior of the shell command ls -1 /usr/include | more
using a C program.
I wrote this code:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
int page[2]; // page is the name of my pipe
pipe(page);
switch (fork()){
case -1:
exit(1);
break;
case 0:;
close(page[1]);
dup2(page[0], 0);
close(page[0]);
execlp("more", "more", NULL);
default:
close(page[0]);
dup2(page[1], 1);
close(page[1]);
execlp("ls", "ls", "-1", "/usr/include", NULL);
break;
}
}
But it only prints one page (as more
would do) and causes some weird behavior that blocks my terminal (forcing me to use reset
to set it back to normal).
I just realized the roles of the parent and the child process were being mixed up. The one to run the more
command should be the parent. Since more
is an interactive command, the terminal will respond better to it as the parent (I'm guessing).
So to solve my issue, I switched the roles of the parent and the child.
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main(){
int page[2]; // page is the name of my pipe
pipe(page);
switch (fork()){
case -1:
exit(1);
break;
case 0:;
close(page[0]);
dup2(page[1], 1);
close(page[1]);
execlp("ls", "ls", "-1", "/usr/include", NULL);
break;
default:
close(page[1]);
dup2(page[0], 0);
close(page[0]);
execlp("more", "more", NULL);
}
}
WHY DOES THIS SOLVES THE PROBLEM? (I still do not clearly understand why it worked!)