【发布时间】:2014-03-20 23:20:49
【问题描述】:
我需要一些帮助来模拟“|” unix 中的命令。我需要能够将第一个参数的输出用作第二个参数的输入,例如 ls 等等。到目前为止我得到了这段代码,但我只是停留在这一点上。任何和所有的帮助都会有所帮助。-谢谢。
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
int main(int argc, char ** words)
{
char** args;
char *cmd1[2] = { words[1], 0 };
char *cmd2[2] = { words[2], 0 };
int colon, arg1 ,i, pid, status;
int thepipe[2];
char ch;
args = (char **) malloc(argc*(sizeof(char*)));
colon = -1;
for (i=0;(i<argc); i=i+1){
if (strcmp(words[i],":") == 0) {
colon = i;
}
else {}
}
pipe(thepipe);
arg1 = colon;
arg1 = arg1 - 1;
for (i=0;(i<arg1); i=i+1){
args[i] = (char*) (malloc(strlen(words[i+1])+1));
strcpy(args[i], words[i+1]);
}
args[argc] = NULL;
pid = fork();
if (pid == 0) {
wait(&pid);
dup2(thepipe[1], 1);
close(thepipe[0]);
printf("in new\n");
execvp(*args, cmd1);
}
else {
close(thepipe[1]);
printf("in old\n");
while ((status=read(thepipe[0],&ch,1)) > 0){
execvp(*args, cmd2);
}
}
}
【问题讨论】:
-
你找错树了。这不是程序级实用程序,而是 bash 本身执行此操作。
-
我明白,但我需要在不使用“|”的情况下复制它。
-
欢迎来到 Stack Overflow。请尽快阅读About 页面。您是否查找过相关问题。 SO 13636252 C Minishell Adding Pipelines 可能是相关的;其他几百人也可能如此。您应该丢失
else {}行。 -
man dup2您需要将标准输入/标准输出与管道的相应端相关联。 -
@ciphermagi - 这是标准的第一年作业。
标签: c input fork output piping