如何将LinuxWC命令与char数组一起使用?

如何将LinuxWC命令与char数组一起使用?,linux,command,pipe,wc,execl,Linux,Command,Pipe,Wc,Execl,嗨~我正在制作一个实现pipe命令的示例程序 在这个程序中,我试图实现“cat somefile.txt | wc”命令 所以我调用了fork()两次,我使用第一个子进程将“cat somefile.txt”的结果发送到fd[1] 然后,第二个子进程将结果从fd[0]获取到文本数组。(我确认它成功读取数据并将数据存储到文本数组) 最后,我要做的是调用execl函数,该函数以文本数组作为参数运行wc命令。但正如您所知,wc需要文件名。当然,最终的输出不是我想要的。。所以我现在有麻烦了 我搜索了ex

嗨~我正在制作一个实现pipe命令的示例程序

在这个程序中,我试图实现“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;
}
#包括
#包括
#包括
#包括
#包括
#包括
字符文本[80];
int main(int argc,char*argv[]){
int-fd[2];
如果(管道(fd)=-1){
perror(argv[0]);
出口(1);
}
如果(fork()==0){//执行cat somefile.txt
dup2(fd[1],1);
关闭(fd[0]);关闭(fd[1]);
execl(“/bin/cat”,“cat”,“somefile.txt”,“char*)0);
出口(127);
}
如果(fork()==0){//执行wc并从cat somefile.txt获取数据
dup2(fd[0],0);
关闭(fd[0]);关闭(fd[1]);
read_to_nl(text);//我定义了它,但没有发布它。无论如何,我确认它成功地将结果从fd[0]获取到文本数组
execl(“/usr/bin/wc”,“wc”,text,(char*)0);//如何设置参数以完成命令“cat somefile.txt | wc”?
出口(127);
}
关闭(fd[0]);关闭(fd[1]);
while(wait((int*)0)!=-1);
返回0;
}

“但正如您所知,wc需要文件名…”-
wc
将从stdin读取<代码>cat foobar.txt | wc-c工作正常。只需将
cat
的stdout连接到
wc
的stdin即可。谢谢您的回答。顺便说一下,我想在运行wc命令时从text(即char数组)获取数据。