【问题标题】:C++ Linux system() ouputs weird in combination with printf();C++ Linux system() 结合 printf() 输出奇怪;
【发布时间】:2012-10-07 09:21:28
【问题描述】:

我想在 Linux 上用 C++ 获取 CPU 的名称和时钟速度。但到目前为止,对我来说效果并不好。现在我正在使用这段代码:

printf("\033[1;32m[ OK ]\033[0m Initializing...\n");
printf("\033[1m[INFO]\033[0m CPU name: ");
system("grep -i --color 'model name' /proc/cpuinfo | uniq | sed -e 's/model name//' |    sed -e 's/: //' | sed -e 's/          //' | sed -e 's/@.*//'");
printf("\n");
printf("\033[1m[INFO]\033[0m CPU speed: ");
system("grep -i --color 'model name' /proc/cpuinfo | uniq | sed -e 's/.*@//'");
printf("\n");

现在,所需的输出应该(在我的机器上)是这样的:

[ OK ] Initializing...
[INFO] CPU name: Intel(R) Xeon(R) CPU X5365  
[INFO] CPU speed: 3.00GHz

但这不是它给我的。它给出了这种奇怪的结构:

[ OK ] Initializing...
     Intel(R) Xeon(R) CPU X5365  
[INFO] CPU name: 
 3.00GHz
[INFO] CPU speed:

有谁知道如何处理这个?无论如何,Tnx。

【问题讨论】:

  • 也许popen 可能对你有用。

标签: c++ linux system printf cpu


【解决方案1】:

在调用system之前需要刷新输出流,否则打印出来的字符串会被缓冲。打印 \n 刷新(假设 stdout 是行缓冲的,如果您正在写入终端,通常会出现这种情况),但打印没有它的行不一定会刷新。

尝试添加:

fflush(stdout);

在您拨打system 之前。

fflush<cstdio> 中。)

【讨论】:

  • 系统是否专门保证了“\n flushes”?
  • @LucDanton 否。特别是 '\n' 如果您不写入终端,则不会刷新流。
  • @LucDanton:它在 POSIX 中用于行缓冲流 (pubs.opengroup.org/onlinepubs/9699919799/functions/…)。完全缓冲的流只需要刷新完整的缓冲区。
  • 它在 C 标准中(7.19.2 Streams,甚至也适用于 C++ 的位之一),因此它也适用于非 POSIX 系统。
  • @hvd:C99 在关于流缓冲模式的段落中说:“对这些特性的支持是实现定义的,......”(§7.19.3/3),POSIX 重复,所以它实际上可能不适用于 C 实现甚至 POSIX :(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 2022-01-12
  • 2021-09-23
  • 1970-01-01
  • 2016-01-31
相关资源
最近更新 更多