I am writing a program that is supposed to run 2 unix commands using 2 separate processes and using pipes i send the output of 1 into the input of another. I have the program running through but for some reason it shows output for the first command and does not seem to pipe the output to the second command and run it. Hers is my code (I tried to comment to make it easier to go through):
I am using a copy of linux mint and geany is my editor.
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <unistd.h>
usingnamespace std;
int main()
{
char *cmd1[] = { "/bin/ls", "-l", "/", 0 };
char *cmd2[] = { "usr/bin/wc", "-w", "/", 0 };
int pipefd[2], rs;
rs = pipe(pipefd);
if (rs < 0)
{
perror("pipe");
exit(EXIT_FAILURE);
}
if(rs == 0)
{ // Child process
// close write end of pipe
close(pipefd[1]);
// close standard input
close(0);
// duplicate read end of pipe
// into standard input
dup(pipefd[0]);
// close read end of pipe
close(pipefd[0]);
// run wc
rs = execvp(cmd1[0], cmd1);
if (rs < 0)
{
perror("execl");
exit(EXIT_FAILURE);
}
}
else
{ // Parent process
// close read end of pipe,
// keep write end open
close(pipefd[0]);
// close standard output
close(1);
// duplicate write end of pipe
// into standard output
dup(pipefd[1]);
// close write end of pipe
close(pipefd[1]);
// run ls
rs = execvp(cmd2[0], cmd2);
if(rs < 0)
{
perror("execl");
exit(EXIT_FAILURE);
}
}
return 0;
}
added the forks but this time it runs but will not end. It shows the output of the ls command. I am going based on notes I have. Do I need to take the output out of the pipe into a buffer and pass it to the wc command as an argument?
If you check out the man page on execvp it has the line: "The exec() family of functions replaces the current process image with a new process image." So your program is no longer running after the execvp() call.
I think you have to fork() to make two processes, and then execvp() in one, and proceed in the other to fork() again etc.