Actual source code: smatlab.c

  1: #include <petscsys.h>

  3: /*@C
  4:   PetscStartMatlab - starts up MATLAB with a MATLAB script

  6:   Logically Collective, but only MPI rank 0 in the communicator does anything

  8:   Input Parameters:
  9: + comm    - MPI communicator
 10: . machine - optional machine to run MATLAB on
 11: - script  - name of script (without the .m)

 13:   Output Parameter:
 14: . fp - a file pointer returned from `PetscPOpen()`

 16:   Level: intermediate

 18:   Notes:
 19:   This starts up a "regular" MATLAB interactive session, it does not start the MATLAB Engine, this is controlled with `PetscMatlabEngine`

 21:   Warning, this overwrites your `matlab/startup.m` file

 23:   The script must be in your MATLAB path or current directory

 25: .seealso: `PetscPOpen()`, `PetscPClose()`, `PetscMatlabEngine`
 26: @*/
 27: PetscErrorCode PetscStartMatlab(MPI_Comm comm, const char machine[], const char script[], FILE **fp)
 28: {
 29:   FILE *fd;
 30:   char  command[512];
 31: #if defined(PETSC_HAVE_UCBPS) && defined(PETSC_HAVE_POPEN)
 32:   char        buf[1024], *found;
 33:   PetscMPIInt rank;
 34: #endif

 36:   PetscFunctionBegin;
 37: #if defined(PETSC_HAVE_UCBPS) && defined(PETSC_HAVE_POPEN)
 38:   /* check if MATLAB is not already running */
 39:   PetscCall(PetscPOpen(comm, machine, "/usr/ucb/ps -ugxww | grep matlab | grep -v grep", "r", &fd));
 40:   PetscCallMPI(MPI_Comm_rank(comm, &rank));
 41:   if (rank == 0) found = fgets(buf, 1024, fd);
 42:   PetscCallMPI(MPI_Bcast(&found, 1, MPI_CHAR, 0, comm));
 43:   PetscCall(PetscPClose(comm, fd));
 44:   if (found) PetscFunctionReturn(PETSC_SUCCESS);
 45: #endif

 47:   if (script) {
 48:     /* the remote machine won't know about current directory, so add it to MATLAB path */
 49:     /* the extra \" are to protect possible () in the script command from the shell */
 50:     PetscCall(PetscSNPrintf(command, PETSC_STATIC_ARRAY_LENGTH(command), "echo \"delete ${HOMEDIRECTORY}/matlab/startup.m ; path(path,'${WORKINGDIRECTORY}'); %s  \" > ${HOMEDIRECTORY}/matlab/startup.m", script));
 51: #if defined(PETSC_HAVE_POPEN)
 52:     PetscCall(PetscPOpen(comm, machine, command, "r", &fd));
 53:     PetscCall(PetscPClose(comm, fd));
 54: #endif
 55:   }
 56: #if defined(PETSC_HAVE_POPEN)
 57:   PetscCall(PetscPOpen(comm, machine, "xterm -display ${DISPLAY} -e matlab -nosplash", "r", fp));
 58: #endif
 59:   PetscFunctionReturn(PETSC_SUCCESS);
 60: }