【发布时间】:2014-02-18 08:55:40
【问题描述】:
我学习 cpp 已经有一段时间了,我一直想知道程序之间如何交互以及如何编写这样的行为。
我的目标是学习如何为简单游戏(扫雷...)和启动时的汽车行为编写机器人代码。
我想知道有哪些工具和库,以及您是否可以推荐一些关于该主题的好教程/书籍。我更喜欢从高级方法开始。
我使用 Windows 和 linux。
【问题讨论】:
-
汽车行为?您的意思可能是“自动行为”
我学习 cpp 已经有一段时间了,我一直想知道程序之间如何交互以及如何编写这样的行为。
我的目标是学习如何为简单游戏(扫雷...)和启动时的汽车行为编写机器人代码。
我想知道有哪些工具和库,以及您是否可以推荐一些关于该主题的好教程/书籍。我更喜欢从高级方法开始。
我使用 Windows 和 linux。
【问题讨论】:
查看Inter-Process Communication (IPC)。
Boost.Interprocess 将帮助抽象出每个平台之间的一些差异。
格拉斯哥流程示例
#include <cstdio>
#include <string>
#include <thread>
#include <chrono>
#include <cstdlib>
#include <boost/interprocess/creation_tags.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
using std::string;
using std::char_traits;
using std::chrono::seconds;
using boost::interprocess::allocator;
using boost::interprocess::create_only;
using boost::interprocess::basic_string;
using boost::interprocess::shared_memory_object;
using boost::interprocess::managed_shared_memory;
typedef allocator< char, managed_shared_memory::segment_manager > shared_string_allocator;
typedef basic_string< char, char_traits< char >, shared_string_allocator > shared_string;
int main( int, char** )
{
const char* TAG = "IPC-Example";
const size_t LIMIT = 1024;
shared_memory_object::remove( TAG );
managed_shared_memory wormhole( create_only, TAG, LIMIT );
wormhole.construct< shared_string >( "developer" )( "You call that a capital city?", wormhole.get_segment_manager( ) );
std::this_thread::sleep_for( seconds( 10 * 60 ) );
return EXIT_SUCCESS;
}
爱丁堡流程示例
#include <cstdio>
#include <string>
#include <cstdlib>
#include <boost/interprocess/creation_tags.hpp>
#include <boost/interprocess/containers/string.hpp>
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
#include <boost/interprocess/managed_shared_memory.hpp>
using std::pair;
using std::string;
using std::char_traits;
using boost::interprocess::allocator;
using boost::interprocess::basic_string;
using boost::interprocess::open_or_create;
using boost::interprocess::shared_memory_object;
using boost::interprocess::managed_shared_memory;
typedef allocator< char, managed_shared_memory::segment_manager > shared_string_allocator;
typedef basic_string< char, char_traits< char >, shared_string_allocator > shared_string;
int main( int, char** )
{
const char* TAG = "IPC-Example";
const size_t LIMIT = 1024;
managed_shared_memory wormhole( open_or_create, TAG, LIMIT );
auto item = wormhole.find< shared_string >( "developer" );
auto content = item.first;
auto count = item.second;
printf( "Received %lu item.\n", count );
printf( "First items content: %s.\n", content->data( ) );
return EXIT_SUCCESS;
}
构建
g++ -std=c++11 -o glasgow glasgow.cpp -lpthread -lrt
g++ -std=c++11 -o edinburgh edinburgh.cpp -lpthread -lrt
执行
./爱丁堡
./格拉斯哥
输出
收到 1 件商品。
第一项内容:你称那是首都?
【讨论】: