Hi~ I'm just making sample program which implements pipe command.
In this program, I'm trying to implement "cat somefile.txt | wc" command..
So I called fork() twice, I used first child process for sending results of "cat somefile.txt" to fd[1].
After that second child process gets the result from fd[0] to text array. (I confirmed it successfully reads and stores datas to text array)
So lastly, what I have to do is to call execl function running wc command with text array as arguments. But as you know, wc needs filename. Of course the final output is not what I wanted.. So I'm in trouble now.
I searched execl , wc but I couldn't find any infos which says wc command can be used with char array.
Do you have any ideas to solve this?
Here's code..
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char text[80];
int main(int argc,char * argv[]){
int fd[2];
if(pipe(fd) == -1){
perror(argv[0]);
exit(1);
}
if(fork() == 0){ // execute cat somefile.txt
dup2(fd[1],1);
close(fd[0]); close(fd[1]);
execl("/bin/cat","cat","somefile.txt",(char *)0);
exit(127);
}
if(fork() == 0){ // execute wc and get datas from cat somefile.txt
dup2(fd[0],0);
close(fd[0]); close(fd[1]);
read_to_nl(text); // I defined but didn't post it. Anyway I confirmed it successfully get results from fd[0] to text array
execl("/usr/bin/wc","wc",text,(char *)0); // how to set arguments to complete command "cat somefile.txt | wc"?
exit(127);
}
close(fd[0]); close(fd[1]);
while(wait((int *) 0) != -1);
return 0;
}