I'm writing pseudo-shell and now write parallel-command functionality. In this question ( Differences between fork and exec ) I'm found how I can call execv
with returning to my code execution. But I don't understand how I can call two parallel programms with continue after. How I see it:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
char *argv_for_program_1[] = {"ls" , NULL};
int pid_1 = fork();
if (pid_1 == 0)
{
execv("/usr/bin/ls" , argv_for_program_1); //print ls
}
char *argv_for_program_2[] = {"pwd" , NULL};
int pid_2 = fork();
if (pid_2 == 0)
{
execv("/usr/bin/pwd" , argv_for_program_2); //print pwd
}
wait(0);
printf("continue"); //print continue
}
But this code run ls -> continue -> pwd. What should I change?
This code should fix it( two wait
) :
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main()
{
char *argv_for_program_1[] = {"ls" , NULL};
int pid_1 = fork();
if (pid_1 == 0)
{
execv("/usr/bin/ls" , argv_for_program_1); //print ls
}
char *argv_for_program_2[] = {"pwd" , NULL};
int pid_2 = fork();
if (pid_2 == 0)
{
execv("/usr/bin/pwd" , argv_for_program_2); //print pwd
}
wait(0);
wait(0); //!!!
printf("continue"); //print continue
}