Note there is a whole family of spawn…() routines to choose from,
depending on what suits you best.
example1.c: without a signal handler
#include <libc.h>
int main()
{
int i;
pid_t pid1;
pid_t pid2;
pid_t pid3;
pid_t pid;
int stat_loc;
pid1 = spawnlp(P_NOWAIT,"sleep","sleep","3",NULL);
fprintf(stderr,"Spawned process %d\n",pid1);
pid2 = spawnlp(P_NOWAIT,"sleep","sleep","3",NULL);
fprintf(stderr,"Spawned process %d\n",pid2);
pid3 = spawnlp(P_NOWAIT,"sleep","sleep","3",NULL);
fprintf(stderr,"Spawned process %d\n",pid3);
for(i=0;i<3;i++)
{
pid = wait(&stat_loc);
fprintf(stderr,"PID %d ended with rc %d\n",pid,stat_loc);
}
}
example2.c: with a signal handler
#include <libc.h>
#include <signal.h>
void my_handler(int sig);
int main(void);
int main()
{
int i;
pid_t pid1;
pid_t pid2;
pid_t pid3;
signal(SIGCHLD, my_handler);
pid1 = spawnlp(P_NOWAIT,"sleep","sleep","3",NULL);
fprintf(stderr,"Spawned process %d\n",pid1);
pid2 = spawnlp(P_NOWAIT,"sleep","sleep","3",NULL);
fprintf(stderr,"Spawned process %d\n",pid2);
pid3 = spawnlp(P_NOWAIT,"sleep","sleep","3",NULL);
fprintf(stderr,"Spawned process %d\n",pid3);
sleep(5);
for(i=0;i<3;i++)
{
sleep(4);
}
}
void my_handler(int sig)
{
pid_t pid;
int stat_loc;
fprintf(stderr,"In Signal Handler signal %d\n",sig);
pid = wait(&stat_loc);
fprintf(stderr,"PID %d ended with rc %d\n",pid,stat_loc);
}