【发布时间】:2018-08-26 09:44:28
【问题描述】:
我尝试读取 mpstat 命令的输出(每秒收集 cpu 信息,即:“mptstat -P ALL 1”)以获取有关 cpu 和核心使用情况的信息。在多核 cpu 上,刚读取第一个测量值后,我得到了一个意外的“文件结束”状态。
似乎 mpstat 以这样一种方式格式化其输出,即所有内核的测量值用空行分隔。
我使用了 async_read_until,其分隔符等于 '\n'。
请在下面找到一个小型复制器。使用此复制器,我得到以下信息:
Enter handle_read
handle_read got data: --Linux 4.13.0-46-generic (pierre) 26/08/2018 _x86_64_ (4 CPU)
--Enter handle_read
handle_read got data: --
11:39:11 CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle
11:39:11 all--Enter handle_read
handle_read got data: -- 5,69 0,06 2,90 0,20 0,00 0,02 0,00 0,00 0,00 91,13
11:39:11 0 5,95 0,05--Enter handle_read
handle_read got data: -- 2,80 0,13 0,00 0,01 0,00 0,00 0,00 91,06
11:39:11 1 5,24 0,01 2,50 0,14 0,00 0,02 0,00 0,00 0,00 92,09
11:39:11 2 6,30 0,17--Enter handle_read
handle_read got data: -- 2,29 0,36 0,00 0,04 0,00 0,00 0,00 90,85
11:39:11 3 5,28 0,01 4,01 0,17 0,00 0,00 0,00 0,00 0,00 90,52
--Enter handle_read
Problem while trying to read mpstat data: End of file
基本上,我能够接收到第一次测量结果,但之后我立即得到“文件结束”。看起来 mpstat 发出的空行是我得到“行尾”指示的原因......但我不明白为什么......
有人可以提供帮助吗?非常感谢。
#include <boost/asio.hpp>
#include <unistd.h>
#include <iostream>
#define PIPE_READ 0
#define PIPE_WRITE 1
#define ENDOFLINE "\n"
static boost::asio::streambuf data;
static std::shared_ptr<boost::asio::posix::stream_descriptor> cpuLoadDataStream;
static void handle_read(const boost::system::error_code& error, std::size_t bytes_transferred) {
printf("Enter handle_read\n");
if (error == boost::system::errc::success) {
if (data.size() > 0) {
std::string dataReceived((std::istreambuf_iterator<char>(&data)), std::istreambuf_iterator<char>());
std::cout << "handle_read got data: " << "--" << dataReceived << "--";
}
boost::asio::async_read_until(*cpuLoadDataStream, data, ENDOFLINE, handle_read);
} else {
std::cout << "Problem while trying to read mpstat data: " << error.message() << std::endl;
}
}
int main() {
int pipeFd[2];
boost::asio::io_service ioService;
if (pipe(pipeFd) < 0) {
std::cout << "pipe error" << std::endl;
exit(EXIT_FAILURE);
}
int pid;
if ((pid = fork()) == 0) {
// son
close(pipeFd[PIPE_READ]);
if (dup2(pipeFd[PIPE_WRITE], STDOUT_FILENO) == -1) {
std::cout << "dup2 error" << std::endl;
exit(EXIT_FAILURE);
}
close(pipeFd[PIPE_WRITE]);
if (execlp("mpstat", "1", "-P", "ALL", 0) == -1) {
std::cout << "execlp error" << std::endl;
exit(EXIT_FAILURE);
}
} else {
// parent
if (pid == -1) {
std::cout << "fork error" << std::endl;
exit(EXIT_FAILURE);
} else {
close(pipeFd[PIPE_WRITE]);
cpuLoadDataStream = std::make_shared<boost::asio::posix::stream_descriptor>(ioService, ::dup(pipeFd[PIPE_READ]));
boost::asio::async_read_until(*cpuLoadDataStream, data, ENDOFLINE, handle_read);
}
}
ioService.run();
return 1;
}
【问题讨论】:
标签: c++ boost-asio child-process