问题描述:网络中的两台不同的Unix机器上运行着两个进程。将简单消息(例如“嗨!!”)从一台机器传递到另一台机器的最简单方法是什么?我知道有很多IPC方法,但最简单的方法是什么?
Boost MPI在我的场景中有用吗?我正在使用C ++实现。
答案 0 :(得分:2)
套接字。这是一个套接字tutorial。一旦你有套接字,你也可以使用boost sockets
答案 1 :(得分:2)
使用套接字(我建议使用boost套接字)或查看ZeroMQ。 ZeroMQ实际上可能更容易,因为它保证始终接收完整的消息。
答案 2 :(得分:1)
这很简单吗? (使用纯MPI标准调用,没有任何第三方库,如Boost.MPI
)
#include <string>
#include <iostream>
#include <mpi.h>
using namespace std;
int main (int argc, char **argv) {
// Initialise the MPI library
MPI_Init(&argc, &argv);
int rank, size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (size != 2) {
if (rank == 0)
cout << "ERROR: You must run this program with 2 processes" << endl;
MPI_Abort(MPI_COMM_WORLD, 0);
}
if (rank == 0) {
// Rank 0 sends the message
string hi = "Hi!";
MPI_Send((void*)hi.c_str(), hi.length()+1, MPI_CHAR,
1, 0, MPI_COMM_WORLD);
}
else {
// Rank 1 receives the message
// Probe for a message and get its actual size
MPI_Status status;
MPI_Probe(0, 0, MPI_COMM_WORLD, &status);
int len;
MPI_Get_count(&status, MPI_CHAR, &len);
// Allocate buffer space for the message and receive it
char *message = new char[len];
MPI_Recv(message, len, MPI_CHAR,
0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
cout << "Rank 1 received: " << message << endl;
delete [] message;
}
MPI_Finalize();
return 0;
}
与mpic++ -o mpihi.exe mpihi.cc
编译并执行:
$ mpiexec -np 2 ./mpihi.exe
Rank 1 received: Hi!
如果预先修复了消息的长度,则可以简化代码。可以使用Boost.MPI
进一步简化它,但我从未使用它,因此我无法为您提供示例。
MPI的优点在于其保证的消息传递以及它抽象互连细节的方式。您可以通过向mpiexec
提供适当的选项来更改两个MPI流程的位置。如果两个进程都放在同一物理节点上,则将使用共享内存来传递消息。如果放在不同的节点上,将使用一些网络机制。
当然,这完全取决于您的需求。 MPI库是复杂的代码片段,具有许多支持基础结构,例如您需要通过专用的启动程序(大多数情况下为mpiexec
或mpirun
)运行代码,并且您无法使用MPI简单地连接两个随机进程(即您真的拥有通过mpiexec
/ mpirun
)启动它们。