C++ 在c++;我的程序卡住了,我该如何继续?

C++ 在c++;我的程序卡住了,我该如何继续?,c++,linux,terminal,C++,Linux,Terminal,我正在制作一个磁盘实用工具,它获取diskstats(在linux中)并从中计算值。我的基本问题是,当system()调用发生时,程序挂起在那里 system("grep 'sda ' /proc/diskstats | tee \"report.txt\""); ifstream inStream; inStream.open("report.txt"); if (inStream.fail()) { cout << "Report gathering f

我正在制作一个磁盘实用工具,它获取diskstats(在linux中)并从中计算值。我的基本问题是,当system()调用发生时,程序挂起在那里

   system("grep 'sda ' /proc/diskstats | tee \"report.txt\"");
   ifstream inStream;
   inStream.open("report.txt");
if (inStream.fail()) {
    cout << "Report gathering failed." << endl;
    return;
}
while (!inStream.eof()) {
    inStream.ignore();
    inStream.ignore();
    inStream.ignore();
    inStream >> numReads1;
    inStream.ignore();
    inStream >> sectorReads1;
    inStream.ignore();
    inStream >> numWrites1;
    inStream.ignore();
    inStream >> sectorWrites1;
    inStream.ignore();
    inStream.ignore();
    inStream.ignore();
    inStream.ignore();
}
system(“grep'sda'/proc/diskstats|tee\'report.txt\”;
流内流;
inStream.open(“report.txt”);
if(inStream.fail()){
无法计数1;
inStream.ignore();
河道内>>路段1;
inStream.ignore();
流内>>数值1;
inStream.ignore();
流内>>扇区写入1;
inStream.ignore();
inStream.ignore();
inStream.ignore();
inStream.ignore();
}
system(“grep'sda'/proc/diskstats|tee\'report.txt\”

你为什么这么做?当然它会挂起来的
tee
将所有输入复制到标准输出和指定为
tee
参数的每个文件。您没有从
tee
的标准输出读取任何内容。如果有足够的匹配项,输出缓冲区将填满,进程将挂起

使用
系统
可以做的是

system("grep 'sda ' /proc/diskstats > report.txt");
report.txt
周围不需要引号,也不需要
tee
。但是,如果您不需要该文件,则没有理由编写该文件。您可以使用
popen

FILE* grep_sda = popen (""grep 'sda ' /proc/diskstats", "r");
请注意,
popen
的结果是一个
文件
指针。这里有三种选择:

  • 使用C样式I/O从该
    文件
    指针读取
  • <> LI>如果幸运的话,有些系统为<代码> STD::FStuts提供非标准构造函数,它从C流构建C++文件流。
  • 可能会有一个提振解决方案。我不能在工作中使用Boost,不要在工作之外使用它

另一个选择是绕过
grep
的使用。这里不需要
grep
,因为模式非常简单。打开文件,作为C++代码> STD::IFStuts,从它使用“<代码> STD::GETLION<代码> > >与<代码> STD::查找< /COD>匹配的过滤行,然后分析匹配的行。

A
ptrace
在您的程序上可能会出现有趣的数据。我首先使用
popen
而不是
system
。您是否能够独立于您的程序在bash shell中运行该命令?它是否正常运行?有比使用<代码>系统< /> >和中间文件更好的C++方式:-大多数都是围绕代码< Pope<代码> >。你真的打算使用<代码> TE/<代码>吗?尝试用输出重排替换三通管