主进程如何将子进程的标准输出重定向到文件中

lion7beck 2018-08-30 10:46:34
环境:linux下用C++编程。
子进程是客户以bin文件形式提供的,我负责主进程开发,会以popen("/*bin文件路径*/")的形式启动子进程,客户提供的bin文件在子进程中执行。但是客户的bin执行时会打印很多log到命令行窗口。。
请教下大家:我能在主进程中将子进程的输出从stdout重定向到其它文件中吗?
非常感谢!
...全文
778 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
赵4老师 2018-08-30
  • 打赏
  • 举报
回复
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
pid_t rw_popen(char* cmd, FILE **rfile, FILE **wfile) {
int pipefd[2],pipefd2[2]; //管道描述符
pid_t pid; //进程描述符

if (pipe(pipefd) < 0) //建立管道
{
printf("rw_popen() pipe create error/n");
return 0;
}
if (pipe(pipefd2) < 0) //建立管道
{
printf("rw_popen() pipe create error/n");
return 0;
}

pid = fork(); //建立子进程

if (pid < 0)
return 0;

if (0 == pid) //子进程中
{
close(pipefd[0]);
dup2(pipefd[1], 1);
close(pipefd[1]);
dup2(pipefd2[0], 0);
close(pipefd2[0]);
close(pipefd[1]);
char *argv[] = { "/bin/sh", "-c", cmd, NULL };
if (execvp("/bin/sh", argv) < 0) //用exec族函数执行命令
exit(1);
}

close(pipefd[1]);
*rfile = fdopen(pipefd[0], "r");
close(pipefd2[0]);
*wfile = fdopen(pipefd2[1], "w");
return pid;
}
void rw_pclose(pid_t pid, FILE *rfile, FILE *wfile) {
int status;
waitpid(pid, &status, 0);
fclose(rfile);
fclose(wfile);
}
int main() {
char buf1[1024];
FILE *file1, *file2;
pid_t pid;
pid = rw_popen("sh", &file1, &file2);
if (pid) {
fputs("pwd;exit;\n",file2);
fflush(file2);
if (fgets(buf1, 1400, file1)) {
puts(buf1);
}
rw_pclose(pid, file1, file2);
}
return 1;
}

sevancheng 2018-08-30
  • 打赏
  • 举报
回复
写批处理调用子进程,将输出重定向到文件,主程序调用批处理
  • 打赏
  • 举报
回复
直接用log写文本文件,不用printf不就好了?
不过你要是没办法干预的话,管道应该可以。
另外,你可以参考一下这个https://blog.csdn.net/lyintong/article/details/51508948
  • 打赏
  • 举报
回复
可以的。如果用Qt,QProcess 会自动接管子进程的 stdin,stdout。不过,注意缓存策略,stdout若不flush,只有在达到缓存门限时,才一股脑输出。为了让自己的进程尽快输出,可以fflush(stdout);
yiyefangzhou24 2018-08-30
  • 打赏
  • 举报
回复
system("./bin >1.txt")

65,186

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧