C 中的管道函数无法处理输入中的两个以上管道是否有修复程序?
Is there a fix for my piping function in C failing to handle more than two pipes in an input?
我有以下递归和分叉函数,它接受一个命令行输入数组,该数组已经被 strsep 拆分(基于单词之间的空格)并且没有重定向(例如 ls | wc 之类的东西)。但是,当代码接受涉及两个以上管道的命令行输入时,第二个管道之后的命令无法获得第二个管道之前的命令的输出。有办法解决这个问题吗?
int *pipefd;
int pipeNum;
int pipes;
int status;
void executeCommandFork(char **commands, int start, int end, int loopNum)
{
char **args;
int i;
int forked = fork();
for (; end < lengthOfArray(commands) && *commands[end] != '|'; end++)
;
int newStart = end + 1;
end--;
args = malloc(end - start + 2);
args[end - start + 1] = NULL;
for (; end >= start; end--)
{
args[end - start] = commands[end];
}
if (forked == 0)
{
if (pipeNum - 2 >= 0)
{
dup2(pipefd[pipeNum - 2], STDIN_FILENO);
}
if (pipeNum + 1 < pipes * 2)
{
dup2(pipefd[pipeNum + 1], STDOUT_FILENO);
}
closePipes();
execvp(args[0], args);
free(args);
}
else
{
pipeNum += 2;
if (pipeNum <= pipes * 2)
{
executeCommandFork(commands, newStart, newStart, loopNum + 1);
}
}
}
void executeCommand(char **commands, int pipes) //this will deal with pipings
{
pipefd = malloc(sizeof(int) * pipes);
int i;
for (i = 0; i < pipes; i++)
{
pipe(pipefd + i * 2);
}
executeCommandFork(commands, 0, 0, 0);
closePipes();
pipeNum = 0;
}
事实证明,pipefd = malloc(sizeof(int) * pipes);
是一条错误的线路。使用 int 指针就可以了。
我有以下递归和分叉函数,它接受一个命令行输入数组,该数组已经被 strsep 拆分(基于单词之间的空格)并且没有重定向(例如 ls | wc 之类的东西)。但是,当代码接受涉及两个以上管道的命令行输入时,第二个管道之后的命令无法获得第二个管道之前的命令的输出。有办法解决这个问题吗?
int *pipefd;
int pipeNum;
int pipes;
int status;
void executeCommandFork(char **commands, int start, int end, int loopNum)
{
char **args;
int i;
int forked = fork();
for (; end < lengthOfArray(commands) && *commands[end] != '|'; end++)
;
int newStart = end + 1;
end--;
args = malloc(end - start + 2);
args[end - start + 1] = NULL;
for (; end >= start; end--)
{
args[end - start] = commands[end];
}
if (forked == 0)
{
if (pipeNum - 2 >= 0)
{
dup2(pipefd[pipeNum - 2], STDIN_FILENO);
}
if (pipeNum + 1 < pipes * 2)
{
dup2(pipefd[pipeNum + 1], STDOUT_FILENO);
}
closePipes();
execvp(args[0], args);
free(args);
}
else
{
pipeNum += 2;
if (pipeNum <= pipes * 2)
{
executeCommandFork(commands, newStart, newStart, loopNum + 1);
}
}
}
void executeCommand(char **commands, int pipes) //this will deal with pipings
{
pipefd = malloc(sizeof(int) * pipes);
int i;
for (i = 0; i < pipes; i++)
{
pipe(pipefd + i * 2);
}
executeCommandFork(commands, 0, 0, 0);
closePipes();
pipeNum = 0;
}
事实证明,pipefd = malloc(sizeof(int) * pipes);
是一条错误的线路。使用 int 指针就可以了。