I am new to C programming. I am trying to run a program given by the path specified by the user using the fork(), exec(), and waitpid() commands. I have been trying to get this to run correctly for hours now and I keep getting errors I am not sure how to troubleshoot, as soon as I solve one error, new ones arise. I was wondering if someone can help me understand why my implementation does not work smoothly?
Many thanks
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char command1[256], command2[256], path[556];
printf("# ");
scanf("%s", command1);
scanf("%s", command2);
scanf("%s", path);
if(strcmp(command1,"quit")==0)
exit(0);
else if(strcmp(command1, "run")==0 && strcmp(command2, "command")==0){
printf("%s", path);
pid_t process;
process = fork();
//fork error
if (process < 0){
perror("fork");
exit(0);
}
else if (process > 0){ //this is the parent process
execl(path, "sh" , "-c", ":ls -l *.c", 0);
}
else {//this is the child process
waitpid(process); //waits until the program terminates
}
}
return 0;
}
It looks to me like you have things swapped. With fork/exec, you generally do the exec in the child process, and the waitpid in the parent process.