C 在循环中执行多个管道
我很快就要想出一个我一直在为linux shell编写的程序,它是用C语言编写的。我一直想让它工作一段时间,现在我决定重新拿起它,在过去的几周里一直在修补它 对于以下代码,请记住名为arrayOfCommands的数组是动态填充的。我的代码使用正在运行的当前命令填充ArrayOfCommand。在我的示例中,我们将运行命令ls-l|wc,arrayOfCommands将填充以下内容,具体取决于循环中的时间:C 在循环中执行多个管道,c,linux,shell,piping,C,Linux,Shell,Piping,我很快就要想出一个我一直在为linux shell编写的程序,它是用C语言编写的。我一直想让它工作一段时间,现在我决定重新拿起它,在过去的几周里一直在修补它 对于以下代码,请记住名为arrayOfCommands的数组是动态填充的。我的代码使用正在运行的当前命令填充ArrayOfCommand。在我的示例中,我们将运行命令ls-l|wc,arrayOfCommands将填充以下内容,具体取决于循环中的时间: //Pass #1 arrayOfCommands[]= ("ls", "-l", NU
//Pass #1
arrayOfCommands[]= ("ls", "-l", NULL)
//Pass #2
arrayOfCommands[]= ("wc", NULL)
以下是我到目前为止的情况:
//PIPING
int do_command(char **args, int pipes) {
// pipes is the number of pipes in the command
// (In our example, one)
// The number of commands is one more than the
// number of pipes (In our example, two)
const int commands = pipes + 1; //Ex: 2
int i = 0;
// Set up the pipes
int pipefds[2*pipes];
for(i = 0; i < pipes; i++){
if(pipe(pipefds + i*2) < 0) {
perror("Couldn't Pipe");
exit(EXIT_FAILURE);
}
}
// Variables
int pid;
int status;
char *str_ptr;
int j = 0;
for (i = 0; i < commands; ++i) {
// A magic function that updates arrayOfCommands with
// the current command goes here. It doesn't make
// sense in the context of the code, so just believe me! :)
// Ex: The contents will be "ls -l" or "wc" depending on
// which time through the loop we are
pid = fork();
if(pid == 0) {
//if not last command
if(i < commands){
if(dup2(pipefds[j + 1], 1) < 0){
perror("dup2");
exit(EXIT_FAILURE);
}
}
//if not first command&& j!= 2*pipes
if(j != 0 ){
if(dup2(pipefds[j-2], 0) < 0){
perror("dup2");
exit(EXIT_FAILURE);
}
}
for(i = 0; i < 2*pipes; i++){
close(pipefds[i]);
}
// Should any of the below inputs be *arrayOfCommands or
// **arrayOfCommands or &arrayOfCommands?
// I'm REALLY bad with pointers
if( execvp(arrayOfCommands, arrayOfCommands) < 0 ){
perror(arrayOfCommands);
exit(EXIT_FAILURE);
}
}
else if(pid < 0){
perror("error");
exit(EXIT_FAILURE);
}
j+=2;
}
for(i = 0; i < 2 * pipes; i++){
close(pipefds[i]);
}
for(i = 0; i < pipes + 1; i++){
}
wait(&status);
}
//管道
int do_命令(字符**参数,int管道){
//pipes是命令中的管道数
//(在我们的例子中,一个)
//命令的数量比
//管道数量(在我们的示例中为两个)
const int commands=pipes+1;//例如:2
int i=0;
//安装管道
内部管道[2*管道];
对于(i=0;i
当我运行此程序时,会出现几个错误:
- dup2:错误的文件描述符
- ls:|:没有这样的文件或目录
- ls:wc:没有这样的文件或目录
//if not last command
if(i < commands)
及
分别通过execvp调用(arrayOfCommands[0],arrayOfCommands)
本质上,arrayOfCommands
的格式必须与int main(int argc,char**argv)
的参数向量(通常为argv
)的格式相同。请阅读以下内容:然后尝试按照所述步骤进行操作
if(i < commands -1)
char * arrayOfCommands[] = {"ls", "-l", NULL};
char * arrayOfCommands[] = {"wc", NULL};