xref: /petsc/src/sys/fileio/smatlab.c (revision 2d30e087755efd99e28fdfe792ffbeb2ee1ea928)
1 
2 #include <petscsys.h>
3 
4 /*@C
5     PetscStartMatlab - starts up MATLAB with a MATLAB script
6 
7     Logically Collective, but only processor zero 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 overwrites your matlab/startup.m file
21 
22      The script must be in your MATLAB path or current directory
23 
24      Assumes that all machines share a common file system
25 
26 .seealso: `PetscPOpen()`, `PetscPClose()`
27 @*/
28 PetscErrorCode PetscStartMatlab(MPI_Comm comm, const char machine[], const char script[], FILE **fp) {
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
35 
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(0);
45 #endif
46 
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     sprintf(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(0);
60 }
61