【发布时间】:2014-09-19 02:05:25
【问题描述】:
我想运行:cat somefile | program > UNIX 系统中的输出文本。
我看过很多东西,比如管道、使用popen、dup2等;我迷路了。
基本代码应该是:
- 使用
program读取cat产生的任何输出并执行一些魔术,然后将数据输出到 outputText。
有什么建议吗?
附言 这些文件是二进制文件。
更新:
我发现这段代码可以与上面规定的命令一起使用......但是 它会做我不想要的事情。
- 如何摆脱
sort?我尝试擦除内容,但随后出现错误并且程序无法运行。 -
cat以二进制方式读取数据 - 以二进制形式向终端输出数据
有什么建议吗?
int main(void)
{
pid_t p;
int status;
int fds[2];
FILE *writeToChild;
char word[50];
if (pipe(fds) == -1)
{
perror("Error creating pipes");
exit(EXIT_FAILURE);
}
switch (p = fork())
{
case 0: //this is the child process
close(fds[1]); //close the write end of the pipe
dup2(fds[0], 0);
close(fds[0]);
execl("/usr/bin/sort", "sort", (char *) 0);
fprintf(stderr, "Failed to exec sort\n");
exit(EXIT_FAILURE);
case -1: //failure to fork case
perror("Could not create child");
exit(EXIT_FAILURE);
default: //this is the parent process
close(fds[0]); //close the read end of the pipe
writeToChild = fdopen(fds[1], "w");
break;
}
if (writeToChild != 0)
{
while (fscanf(stdin, "%49s", word) != EOF)
{
//the below isn't being printed. Why?
fprintf(writeToChild, "%s end of sentence\n", word);
}
fclose(writeToChild);
}
wait(&status);
return 0;
}
【问题讨论】:
-
当您可以将
program的stdin设置为somefile时,为什么还要使用cat来输入它?即program < somefile > outputText -
不幸的是,我的任务指定我必须这样做。
-
并且cat读取的文件是二进制的,如果可能的话输出也应该是二进制的。
-
我需要2个文件吗?一个文件做管道?我注意到许多程序调用 exec(),它们在其中调用特定文件,在我的情况下是程序?所以 pipe.c 会调用 program.c 并以某种方式从 cat 中获取标准输出并将其放入 program.c???
-
如果你,如你所说,应该(家庭作业?)以
cat somefile | program > output运行程序,那么你就走错了路。像这样运行命令使 shell pipe 成为cat的输出到program的输入。这与在程序中设置管道不同。 en.wikipedia.org/wiki/Redirection_(computing)#Piping