Reputation: 396
The program executes, but the final output is not being displayed. I seem to be messing up the pipe lining of outputs.
Removed the checks for failure of execlp(),pipe(),fork() since they aren't contributing to the said problem.
#include "iostream"
#include "stdlib.h"
#include "unistd.h"
#include "wait.h"
#include "stdio.h"
#include "fcntl.h"
using namespace std;
int main(int argc, char **argv)
{
int fd[2],status,status2,fd1[2];
pipe(fd);
pipe(fd1);
char buf[12];
switch(fork())
{
case 0:
close(fd[0]);
dup2(fd[1],1);
close(fd[1]);
execlp("ls","ls",NULL);
exit(0);
break;
default:
waitpid(-1,&status,0);
close(fd[1]);
close(fd1[0]);
dup2(fd1[1],1);
close(fd1[1]);
dup2(fd[0],0);
close(fd[0]);
execlp("wc","wc",NULL);
}
switch(fork())
{
case 0:
close(fd1[1]);
dup2(fd1[0],0);
close(fd1[0]);
execlp("wc","wc",NULL); //this is not being redirected to STDOUT
exit(0);
break;
default:
waitforpid(-1,&status2,0);
}
return 0;
}
Upvotes: 1
Views: 856
Reputation: 754
The exec
family of functions does not spawn separate processes, they replaces the current process instead. As stated in the man page for execlp, execlp
returns control only in case of an error.
So, in case all fork
and execlp
calls succeed, your program cannot reach the third invocation of execlp
, since one of case
s in the first switch
is always executed, and either of them replaces your process.
Meanwhile, I suggest you not to parse the ls
output in real life problems, since file names in UNIX can contain whitespace characters, newlines, etc., that you probably cannot parse, there are other options such as the find
command that can separate file names with '\0'
.
Upvotes: 1
Reputation: 58
Seems like the second fork() won't be executed since the two process will mutate in the execlp instruction to the code of the programs 'ls' and 'wc' . Check if it's that, maybe just changing the execlp instruccion in the default of the first switch to the second switch should be enough.
Upvotes: 1