I am using linux and I want to write a program in c that reads commands from user until I enter stop.For each command the main program will create a process A which will create another process B.The process B will execute the command entered by user.I want to make it work using exec but it only works for one word commands (ex:pwd
, ls
) , if i enter for example ls -l
it says that there is no such file or directory.The code i wrote so far :
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#define N 100
int main() {
char input[N];
scanf(" %[^\n]s",input); //reads from user inputs that can include space
while (strcmp(input,"stop") != 0) { // verifies if entered command == stop
int a;
a = fork();//creates the process A
if (a == -1) {
perror("fork imposibil!");
exit(1);
}
if (a == 0) {
printf("a\n");//i printed that to verify if my fork works
int b;
b = fork();//creates process B
if (b == -1) {
perror("fork imposibil!");
exit(1);
}
if (b == 0) { // the part that makes me problems , i try to use exec to execute the command that is stored in input
printf("b\n");
if (execlp(input,"",(char*) 0) < 0) {
perror("Error exec");
exit(0);
}
exit(0);
}
wait(0);
exit(0);
}
wait(0);
scanf(" %[^\n]s",input);
}
return 0;
}
Can someone help me please ? P.S. I don't think that my code was so impossible to read but i hope it's better now