It is required to use pipe(), fork(), execve() and dup() to implement a simple execution of terminal command with pipe for our homework. So I read about how dup and pipe manipulate the file descriptor, and I produced the code below.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
int pfds[2];
pipe(pfds);
if (!fork()) {
close(1); /* close normal stdout */
dup(pfds[1]); /* make stdout same as pfds[1] */
close(pfds[0]); /* we don't need this */
char *k = {"echo", "one", "two", "three", NULL};
execve("/bin/echo", k, NULL);
} else {
close(0); /* close normal stdin */
dup(pfds[0]); /* make stdin same as pfds[0] */
close(pfds[1]); /* we don't need this */
char *k = {"wc", "-w", NULL};
execve("/usr/bin/wc", k, NULL);
}
return 0;
}
It looks like there's nothing coming out by running the code, I am not sure what else do I need to make it work.
I am expecting out put of 3, as you will see by entering
echo one two three | wc -w
in the terminal. I am using a MacOS by the way.