作者lungswu (宅爸)
看板LinuxDev
标题Re: [问题] 请问要怎抓呼叫外部程式所得的回传值
时间Fri Aug 21 12:11:02 2009
※ 引述《lolo33 (none)》之铭言:
: 请问一下 我想要做到说 利用呼叫system("ls") 执行外部程式
: 但是我想要将结果存在 buffer 中, 而不是直接输出到console
: 请问有办法可以做到吗?
: 感谢
参考一下吧
from
http://zbarbar.blogspot.com/2009/08/blog-post_6471.html
@HOST:~/tmp$ cat redir.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUF_SIZE 1000
int main(void)
{
int fd[2];
char buffer[BUF_SIZE];
pipe(fd);
dup2(fd[1], 1);
memset(buffer, 0x00, BUF_SIZE);
system("ls");
fprintf(stderr,"**** output ****\n");
read(fd[0], buffer, BUF_SIZE);
fprintf(stderr, "%s", buffer);
return 0;
}
@HOST:~/tmp$ gcc -Wall redir.c -o redir
@HOST:~/tmp$ ./redir
**** output ****
dump.txt
redir
redir.c
@HOST:~/tmp$
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 116.59.127.243