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?
CodePudding user response:
Here is your problem with strtok from man : " The strtok() function breaks a string into a sequence of zero or more nonempty tokens. On the first call to strtok(), the string to be parsed should be specified in str. In each sub‐ sequent call that should parse the same string, str must be NULL."
this code should fix it :
...
if ( found_parallel ) { /// !!! this place
printf("%s\n","parallel");
char *name_of_program_1;
name_of_program_1 = strtok(line, separator);
char *temp;
temp = strtok(NULL, separator);
char *name_of_program_2;
name_of_program_2 = strtok(NULL, separator);
char path_1[100] = "/usr/bin/";
strcat(path_1, name_of_program_1);
char path_2[100] = "/usr/bin/";
strcat(path_2, name_of_program_2);
...
CodePudding user response:
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
}