Mpifork.c
From HPC documentation portal
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <math.h>
#include <mpi.h>
void main(int argc, char *argv[])
{
/*################################################*/
/* */
/* ***************** */
/* * OASIS ROUTINE * */
/* * ------------- * */
/* ***************** */
/* */
/* program which launches couple, atmos and ocean */
/* Author: Claude Mercier, Laurent Terray */
/* Updated: Ingo Bethke (2012.05.05) */
/* ------ */
/*################################################*/
int id1, id2, rtc;
/* IO variables. */
FILE *file_ptr;
int masterpid=100000000, pid, status, i;
unsigned int sleeplen;
/* write process id to common file */
pid=getpid();
file_ptr=fopen("pid.txt","a");
fprintf(file_ptr,"%d\n",(int) getpid());
fclose(file_ptr);
/* wait a second to make sure that all ids are written */
sleeplen=1;
sleep(sleeplen);
/* read process id from all processes and check if
this process is the master process (i.e., has lowest id) */
file_ptr=fopen("pid.txt","r");
while(!feof(file_ptr)) {
fscanf(file_ptr, "%d", &pid);
if (pid < masterpid) {
masterpid=pid;
}
}
fclose(file_ptr);
if (masterpid == getpid()){
printf("master pid %d\n",masterpid);
id1 = fork();
if(id1 == -1) {
perror("first FORK failed");
exit(1);
}
if(id1 != 0) {
/* parent */
id2 = fork();
if(id2 == -1) {
perror("second FORK failed");
exit(2);
}
sleep(5);
if (id2 != 0) {
/* still the parent */
/*coupler*/
printf("Launch oasis %d\n",getpid());
rtc = execl("arpege","arpege",0);
perror("EXEC 1 failed");
} else {
/* child 2 */
printf("Launch arpege %d\n",getpid());
execl("oasis","oasis",0);
perror("EXEC 2 failed");
}
} else {
/* child 1 */
printf("Launch micom %d\n",getpid());
execl("micom","micom",0);
perror("EXEC 3 failed");
}
} else {
printf("Launch arpege %d\n",getpid());
execl("arpege","arpege",0);
perror("EXEC 2 failed");
}
}