[mpich-discuss] spawned processes do not shut down

Jonathan Bishop jbishop.rwc at gmail.com
Tue Nov 1 19:04:19 CDT 2011


Sorry, the last message scrambled the code, try again...

#include <sys/types.h>
#include <unistd.h>
#include <iostream>
#include "mpi.h"

using namespace std;

const int BUFSIZE = 1000;
const int NWORKER = 2;

//
-------------------------------------------------------------------------------------------------

static void mpi_send(int dst, const string& s, MPI_Comm comm)
{
  char buf[BUFSIZE];
  strcpy(buf, s.c_str());
  MPI_Send(buf, s.size(), MPI_CHAR, dst, 0, comm);
}

//
-------------------------------------------------------------------------------------------------

static string mpi_recv(int src, MPI_Comm comm)
{
  char buf[BUFSIZE];
  MPI_Status status;
  MPI_Recv(buf, BUFSIZE, MPI_CHAR, src, MPI_ANY_TAG, comm, &status);
  int count;
  MPI_Get_count(&status, MPI_CHAR, &count);
  buf[count] = 0;
  return buf;
}

//
-------------------------------------------------------------------------------------------------

main(int argc, char **argv)
{

  MPI_Init(&argc, &argv);
  MPI_Comm parent;
  MPI_Comm_get_parent(&parent);

  // Master
  if (parent == MPI_COMM_NULL) {
    MPI_Comm intercom = MPI_COMM_NULL;
    while (1) {
      cout << "Enter: ";
      string s;
      cin >> s;
      if (s == "start") {
if (intercom != MPI_COMM_NULL) {
  cout << "already started" << endl;
  continue;
}
cout << "spawn " << argv[0] << endl;
MPI_Comm_spawn(argv[0], MPI_ARGV_NULL, NWORKER, MPI_INFO_NULL, 0,
MPI_COMM_SELF, &intercom, MPI_ERRCODES_IGNORE);
continue;
      }
      if (s == "stop") {
if (intercom == MPI_COMM_NULL) {
  cout << "worker not running" << endl;
  continue;
}
for (int w = 0; w < NWORKER; w++) {
  mpi_send(w, s, intercom);
}
  MPI_Comm_disconnect(&intercom);
intercom = MPI_COMM_NULL;
continue;
      }
      if (s == "exit") {
if (intercom != MPI_COMM_NULL) {
  cout << "need to stop before exit" << endl;
  continue;
}
break;
      }
      if (intercom == MPI_COMM_NULL) {
cout << "need to start" << endl;
continue;
      }
      for (int w = 0; w < NWORKER; w++) {
mpi_send(w, s, intercom);
string t = mpi_recv(w, intercom);
cout << "worker " << w << " returned " << t << endl;
      }
    }
  }

  // Worker
  if (parent != MPI_COMM_NULL) {
    while (1) {
      string s = mpi_recv(0, parent);
      if (s == "stop") {
MPI_Comm_disconnect(&parent);
break;
      }
      mpi_send(0, s, parent);
    }
  }

  MPI_Finalize();
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.mcs.anl.gov/pipermail/mpich-discuss/attachments/20111101/a8ac607c/attachment-0001.htm>


More information about the mpich-discuss mailing list