gpt4 book ai didi

c++ - c++中通过程序实时返回变量

转载 作者:行者123 更新时间:2023-11-30 03:19:41 26 4
gpt4 key购买 nike

我有一个用 C++ 编写的程序。我正在寻找如何使用另一个 C++ 程序实时捕获它的值。例如我在程序中有这样的东西:

int main()
{
int n = 0;
while (true) {
cout << n << endl;
n++;
}
}

这很简单,但代表了我的真实程序是如何工作的,它每隔几毫秒就给 n 赋值。现在我想捕获 n 值并在它们出现在命令窗口中的同时将它们存储在一个新程序中。

最佳答案

我为通过管道进行通信的两个进程制作了一个非常简单的示例。

因为我打算在 coliru 上演示它,所以我不得不将两个进程的代码放在一个程序中。程序是作为编写者还是读者由命令行参数决定。这是源代码:

#include <cstdlib>
#include <chrono>
#include <iostream>
#include <string>
#include <thread>

namespace Writer {

int main()
{
// produce some values
for (int i = 0; i < 10; ++i) {
// consume some time e.g. for reading camera
std::this_thread::sleep_for(std::chrono::duration<int, std::milli>(50));
// determine position
const int x = std::rand(), y = std::rand();
// write values to stream
std::cout << i << ' ' << x << ' ' << y << '\n';
}
// done
return 0;
}

} // namespace Writer

namespace Reader {

int main()
{
// consume some values
for (int i = 0;; ++i) {
// read values
int iW, x, y;
if (!(std::cin >> iW >> x >> y)) break;
// report values
std::cout << i << ": " << iW << ", x: " << x << ", y: " << y << '\n';
}
// report lost input
std::cout << "End of input.\n";
// done
return 0;
}

} // namespace Reader

int main(int argc, char **argv)
{
const std::string arg1 = argc == 2 ? argv[1] : "";
if (arg1 != "-i" && arg1 != "-o") {
std::cerr << "Usage:\n"
<< "a.out -o ... to start the writer\n"
<< "a.out -i ... to start the reader\n";
return -1;
}
if (arg1 == "-o") return Writer::main();
else return Reader::main();
}

编译并开始于:

g++ -std=c++17 -O2 -Wall -pedantic -pthread main.cpp && ./a.out -o | ./a.out -i

输出:

0: 0, x: 1804289383, y: 846930886
1: 1, x: 1681692777, y: 1714636915
2: 2, x: 1957747793, y: 424238335
3: 3, x: 719885386, y: 1649760492
4: 4, x: 596516649, y: 1189641421
5: 5, x: 1025202362, y: 1350490027
6: 6, x: 783368690, y: 1102520059
7: 7, x: 2044897763, y: 1967513926
8: 8, x: 1365180540, y: 1540383426
9: 9, x: 304089172, y: 1303455736
End of input.

Live Demo on coliru

它是这样工作的:

  1. main() 除了评估命令行参数并调用 Reader::main()Writer::main() 之外什么都不做(如果找不到合适的参数则打印错误)。

  2. Writer::main() 产生一些值(延迟 50 毫秒以使其更令人兴奋/真实)并将其写入 std::cout.

  3. Reader::main() 使用从 std::cin 读取的一些值。

就是这样。

真正的魔法就是它的名字:

./a.out -o | ./a.out -i

我不确定 coliru 背后的操作系统和外壳是什么,但它看起来像 Linux。 (它可能也适用于 Windows 10 提示符,但我对此不太熟悉。我主要使用 cygwin64 作为 bash 的粉丝。)

它在两个进程中启动 ./a.out(C++ 编译器的默认输出),一个带有 arg -o,另一个带有 arg -i 。因此,管道符号|将前者的标准输出 channel 连接到后者的标准输入 channel 。 (管道和管道语法的发明是革命性的 Unix 概念之一。发明者想要连接花园软管等工具——我曾经在某处读到过。)

公平地说,我必须承认它是 newbie谁在他的评论中提到了这个想法。

关于c++ - c++中通过程序实时返回变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53459672/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com