【发布时间】:2020-07-03 09:13:43
【问题描述】:
我正在尝试通过 C 中的程序执行ls | wc -l,而不是使用命令行。
这是我当前的工作代码:
int main() {
int pfds[2];
pipe(pfds);
pid_t pid = fork();
if ( pid == 0 ) { /* The child process*/
close(1);
dup(pfds[1]);
close(pfds[0]);
execlp("ls", "ls", NULL);
} else { /* The parent process*/
close(0);
dup(pfds[0]);
close(pfds[1]);
wait(0);
execlp("wc", "wc", "-l", NULL);
}
return 0;
}
如何重写此代码以使用 for 循环?
例如:
for (i=0; i<2; i++) {
// Rewrite the 2-level pipe here
}
稍后,我想扩展 for 循环以执行更多进程,例如 a | b | c | ...
【问题讨论】:
-
您想使用
for循环运行ls | wc -lN 次而不是一次(在您的示例2 中)? -
对于简单的双命令管道没关系,您是否尝试为未知长度的更通用管道解决这个问题?
-
@MarcoBonelli 是的,我正在尝试解决这个问题以获得更通用的管道
-
@HMemon 我想你误解了我的问题。我在问您是否要多次运行完全相同的管道进程 (
ls | wc -l)。您想要那个,还是想要使用for循环来执行更多 个进程,如a | b | c | ...?不清楚你在问什么。您应该在问题中指定这一点。 -
@MarcoBonelli,我想使用 for 循环来执行更多的进程,就像 |乙 | c | ...
标签: c linux operating-system