子进程运行一个 bin 文件,该文件由 Qualcomm 提供。子进程由我开发的父进程调用。
子进程运行时,总会在shell命令中打印大量日志。
那么,我是否能够将 Qualcomm 的输出从 stdout 重定向到父进程中的另一个文件?
如您所知,推动高通更新此 bin 文件几乎是不可能的。
这里的关键部分是 POSIX 函数dup2,它基本上可以让您用一个文件描述符替换另一个文件描述符。如果您使用fork(not ),您实际上可以控制加载其他可执行文件的和system之间的子进程中发生的情况。forkexec*
#include <cstdlib>
extern "C" {
#include <fcntl.h>
#include <unistd.h>
}
#include <stdexcept>
#include <iostream>
pid_t start_child(const char* program, const char* output_filename)
{
pid_t pid = fork();
if (pid < 0) {
// fork failed!
std::perror("fork");
throw std::runtime_error("fork failed");
} else if (pid == 0) {
// This code runs in the child process.
int output_fd = open(output_filename, O_WRONLY | O_CREAT | O_TRUNC,S_IRUSR | S_IWUSR);
if (output_fd < 0) {
std::cerr << "Failed to open log file " << output_filename << ":"
<< std::endl;
std::perror("open");
std::exit(1);
}
// Replace the child's stdout and stderr handles with the log file handle:
if (dup2(output_fd, STDOUT_FILENO) < 0) {
std::perror("dup2 (stdout)");
std::exit(1);
}
if (dup2(output_fd, STDERR_FILENO) < 0) {
std::perror("dup2 (stderr)");
std::exit(1);
}
if (execl(program, program, (char*)nullptr) < 0) {
// These messages will actually go into the file.
std::cerr << "Failed to exec program " << program << ":"
<< std::endl;
std::perror("execl");
std::exit(1);
}
}
return pid;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6470 次 |
| 最近记录: |