I am writing a program that duplicates the command:
grep -cr Thread nachos/ | sort -t : +1.0 -2.0 --numeric --reverse | head --lines=5
My code:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/wait.h>
#define R_FILE "/proc/meminfo"
#define GREP_EXEC "/bin/grep"
#define SORT_EXEC "/bin/sort"
#define HEAD_EXEC "/usr/bin/head"
#define BSIZE 256
int main()
{
int status;
pid_t pid_1, pid_2, pid_3;
int pipefd[4];
//int pipefd[2];
pipe(pipefd);
pipe(pipefd + 2);
pid_1 = fork();
if (pid_1 == 0) {
/* grep process */
dup2(pipefd[1], 1);
close(pipefd[0]);
close(pipefd[1]);
close(pipefd[2]);
close(pipefd[3]);
execl("grep", "-cr", "Thread", "nachos/", (char *) 0);
return 0;
}
pid_2 = fork();
if (pid_2 == 0) {
/* sort process */
dup2(pipefd[0], 0);
dup2(pipefd[3], 1);
close(pipefd[0]);
close(pipefd[1]);
close(pipefd[2]);
close(pipefd[3]);
execl("sort", "-t", ":", "+1.0", "-2.0", "–-numeric", "-–reverse", (char *) 0);
return 0;
}
pid_3 = fork();
if (pid_3 == 0) {
/* head process */
dup2(pipefd[2], 0);
//dup2(pipefd[0], 0);
close(pipefd[0]);
close(pipefd[1]);
close(pipefd[2]);
close(pipefd[3]);
execl("head", "--lines=5", (char *) 0);
return 0;
}
close(STDIN_FILENO);
close(STDOUT_FILENO);
if ((waitpid(pid_1, &status, 0)) == -1) {
fprintf(stderr, "Process 1 encountered an error. ERROR%d", errno);
return EXIT_FAILURE;
}
if ((waitpid(pid_2, &status, 0)) == -1) {
fprintf(stderr, "Process 2 encountered an error. ERROR%d", errno);
return EXIT_FAILURE;
}
if ((waitpid(pid_3, &status, 0)) == -1) {
fprintf(stderr, "Process 3 encountered an error. ERROR%d", errno);
return EXIT_FAILURE;
}
return 0;
}
I don't see what I am doing wrong. I am matching the write of the fd to stdout and likewise for read of the fd to stdin. My pipes seem to be matched up. Yet I get no output. Please any help would be appreciated.