我所以接近找出我用C编写的linux shell编写的程序。我一直想让它工作一段时间,我决定把它拿起来过去几周一直在修补它。
对于以下代码,请记住,动态填充名为 arrayOfCommands 的数组。我的代码使用当前运行的命令填充arrayOfCommands。为了我的例子,我们将运行命令 ls -l | wc 和arrayOfCommands用以下内容填充,具体取决于它在循环中的时间:
//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);
}
当我运行时,我会遇到一些错误:
有人可以帮我弄清楚以下两件事:
答案 0 :(得分:3)
第一件事:
//if not last command
if(i < commands)
应该是
if(i < commands -1)
因为i
从0
转到commands -1
应解决dup2:错误的文件描述符
ls:|:没有这样的文件或目录
ls:wc:没有这样的文件或目录
是由格式错误arrayOfCommands
引起的。它必须由
char * arrayOfCommands[] = {"ls", "-l", NULL};
和
char * arrayOfCommands[] = {"wc", NULL};
分别通过execvp(arrayOfCommands[0], arrayOfCommands)
基本上arrayOfCommands
必须与argv
的参数向量(通常为int main(int argc, char** argv)
)的格式相同。