0

嗨~我只是在制作实现管道命令的示例程序。

在这个程序中,我正在尝试实现“cat somefile.txt | wc”命令。

所以我调用了 fork() 两次,我使用第一个子进程将“cat somefile.txt”的结果发送到 fd[1]。

之后,第二个子进程将结果从 fd[0] 获取到文本数组。(我确认它成功读取并将数据存储到文本数组)

所以最后,我要做的是调用 execl 函数运行 wc 命令,并将文本数组作为参数。但如您所知, wc 需要文件名。当然最终的输出不是我想要的。所以我现在有麻烦了。

我搜索了 execl , wc 但我找不到任何说明 wc 命令可以与 char 数组一起使用的信息。

你有什么想法来解决这个问题吗?





这是代码..

#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;
}
4

0 回答 0