如何从模仿管道的execlp命令中获取输出?
How to grab output from execlp command that imitates pipe?
我有一个 C 程序应该模拟与调用相同的东西:
popen("ls | grep som")
现在我有两个进程,每个进程执行此命令的一部分,第一个的输出是第二个的输入。当我执行程序时,我看到终端中提示了正确的行,但我似乎无法将输出保存为字符串。我总是以 ls 命令打印出的第一件事结束。
示例:
如果 ls 打印出来:
一
二
三
字符串始终等于“一”。
代码如下所示:
int fd[2];
pipe(fd);
pid_t pid1, pid2;
FILE *f;
int pid1 = fork();
if (pid1 == 0) {
dup2(fd[1], STDOUT_FILENO);
close(fd[1]);
close(fd[0]);
execlp("ls", "ls", NULL);
}
int pid2 = fork();
if (pid2 == 0) {
dup2(fd[0], STDIN_FILENO);
close(fd[1]);
close(fd[0]);
execlp("grep", "grep", "som",NULL);
}
f = fdopen(fd[0] ,"r");
// then I read the output with snprintf
//and once again I close fd's
close(fd[0]);
close(fd[1]);
waitpid(// first process)
waitpid(// second process)
为 grep
的标准输出添加另一个管道,并从您的主进程中读取它。
我有一个 C 程序应该模拟与调用相同的东西:
popen("ls | grep som")
现在我有两个进程,每个进程执行此命令的一部分,第一个的输出是第二个的输入。当我执行程序时,我看到终端中提示了正确的行,但我似乎无法将输出保存为字符串。我总是以 ls 命令打印出的第一件事结束。
示例: 如果 ls 打印出来: 一 二 三
字符串始终等于“一”。
代码如下所示:
int fd[2];
pipe(fd);
pid_t pid1, pid2;
FILE *f;
int pid1 = fork();
if (pid1 == 0) {
dup2(fd[1], STDOUT_FILENO);
close(fd[1]);
close(fd[0]);
execlp("ls", "ls", NULL);
}
int pid2 = fork();
if (pid2 == 0) {
dup2(fd[0], STDIN_FILENO);
close(fd[1]);
close(fd[0]);
execlp("grep", "grep", "som",NULL);
}
f = fdopen(fd[0] ,"r");
// then I read the output with snprintf
//and once again I close fd's
close(fd[0]);
close(fd[1]);
waitpid(// first process)
waitpid(// second process)
为 grep
的标准输出添加另一个管道,并从您的主进程中读取它。