xref: /petsc/src/sys/fileio/smatlab.c (revision bcee047adeeb73090d7e36cc71e39fc287cdbb97)
1 
2 #include <petscsys.h>
3 
4 /*@C
5     PetscStartMatlab - starts up MATLAB with a MATLAB script
6 
7     Logically Collective, but only MPI rank 0 in the communicator does anything
8 
9     Input Parameters:
10 +     comm - MPI communicator
11 .     machine - optional machine to run MATLAB on
12 -     script - name of script (without the .m)
13 
14     Output Parameter:
15 .     fp - a file pointer returned from `PetscPOpen()`
16 
17     Level: intermediate
18 
19     Notes:
20     This starts up a "regular" MATLAB interactive session, it does not start the MATLAB Engine, this is controlled with `PetscMatlabEngine`
21 
22     Warning, this overwrites your `matlab/startup.m` file
23 
24      The script must be in your MATLAB path or current directory
25 
26 .seealso: `PetscPOpen()`, `PetscPClose()`, `PetscMatlabEngine`
27 @*/
28 PetscErrorCode PetscStartMatlab(MPI_Comm comm, const char machine[], const char script[], FILE **fp)
29 {
30   FILE *fd;
31   char  command[512];
32 #if defined(PETSC_HAVE_UCBPS) && defined(PETSC_HAVE_POPEN)
33   char        buf[1024], *found;
34   PetscMPIInt rank;
35 #endif
36 
37   PetscFunctionBegin;
38 #if defined(PETSC_HAVE_UCBPS) && defined(PETSC_HAVE_POPEN)
39   /* check if MATLAB is not already running */
40   PetscCall(PetscPOpen(comm, machine, "/usr/ucb/ps -ugxww | grep matlab | grep -v grep", "r", &fd));
41   PetscCallMPI(MPI_Comm_rank(comm, &rank));
42   if (rank == 0) found = fgets(buf, 1024, fd);
43   PetscCallMPI(MPI_Bcast(&found, 1, MPI_CHAR, 0, comm));
44   PetscCall(PetscPClose(comm, fd));
45   if (found) PetscFunctionReturn(PETSC_SUCCESS);
46 #endif
47 
48   if (script) {
49     /* the remote machine won't know about current directory, so add it to MATLAB path */
50     /* the extra \" are to protect possible () in the script command from the shell */
51     PetscCall(PetscSNPrintf(command, PETSC_STATIC_ARRAY_LENGTH(command), "echo \"delete ${HOMEDIRECTORY}/matlab/startup.m ; path(path,'${WORKINGDIRECTORY}'); %s  \" > ${HOMEDIRECTORY}/matlab/startup.m", script));
52 #if defined(PETSC_HAVE_POPEN)
53     PetscCall(PetscPOpen(comm, machine, command, "r", &fd));
54     PetscCall(PetscPClose(comm, fd));
55 #endif
56   }
57 #if defined(PETSC_HAVE_POPEN)
58   PetscCall(PetscPOpen(comm, machine, "xterm -display ${DISPLAY} -e matlab -nosplash", "r", fp));
59 #endif
60   PetscFunctionReturn(PETSC_SUCCESS);
61 }
62