从 exec 获取输出 [英] Grabbing output from exec
问题描述
我正在尝试编写一个 C 程序来获取命令输出,然后我会将其传递给另一个程序.
I'm trying to write a C program that grabs command output and then i'll be passing that to another program.
我遇到了一个问题,我不知道如何获取命令输出并存储它.以下是我所拥有的样本
I'm having an issue, I cant work out how to get the command output and store it. Below is a sample of what I have
if(fork() == 0){
execl("/bin/ls", "ls", "-1", (char *)0);
/* do something with the output here */
}
else{
//*other stuff goes here*
}
所以基本上我想知道是否有任何方法可以从execl"获取输出并将其传递给其他东西(例如,通过将其存储在某种缓冲区中).
so basically im wondering if there is any way i can get the output from the "execl" and pass it to some thing else (e.g. via storing it in some kind of buffer).
建议会很棒.
推荐答案
您必须使用 pipe()
创建从父进程到子进程的管道.然后您必须使用 dup
或 dup2
将 standard 输出
(STDOUT_FILENO) 和 error output
(STDERR_FILENO) 重定向到管道,并在父进程中,从管道中读取.它应该可以工作.
You have to create a pipe from the parent process to the child, using pipe()
.
Then you must redirect standard ouput
(STDOUT_FILENO) and error output
(STDERR_FILENO) using dup
or dup2
to the pipe, and in the parent process, read from the pipe.
It should work.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define die(e) do { fprintf(stderr, "%s
", e); exit(EXIT_FAILURE); } while (0);
int main() {
int link[2];
pid_t pid;
char foo[4096];
if (pipe(link)==-1)
die("pipe");
if ((pid = fork()) == -1)
die("fork");
if(pid == 0) {
dup2 (link[1], STDOUT_FILENO);
close(link[0]);
close(link[1]);
execl("/bin/ls", "ls", "-1", (char *)0);
die("execl");
} else {
close(link[1]);
int nbytes = read(link[0], foo, sizeof(foo));
printf("Output: (%.*s)
", nbytes, foo);
wait(NULL);
}
return 0;
}
这篇关于从 exec 获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!