Reputation: 330
I am student developer and beginner in C programming language. I have a task and I did not find a clear solution according to my level. I want to run exec() function in child process. I created parent and child using fork(). It's OK. But my code is only running command like ls , pwd
etc. If I want to write ls -l
, it does not work command like that. What should I do ? Could you help me at this issue ?
My output for ls
:
ls
a.out main.c
2006152 ms
My output for ls -l
:
ls -l
Error exec: No such file or directory
3627824 ms
My code is :
#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
void ChildProcess ();
void ParentProcess ();
struct timeval start, end;
int main () {
gettimeofday (&start, NULL);
pid_t pid;
pid = fork ();
if (pid == 0){
ChildProcess ();
}
else {
wait (NULL);
ParentProcess ();
}
return 0;
}
void ChildProcess () {
char input[N];
scanf (" %[^\n]s", input);
if (execlp (input, "", (char *) 0) < 0){
perror ("Error exec");
exit (0);}
}
void ParentProcess () {
gettimeofday (&end, NULL);
printf ("%ld %s \n", ((end.tv_sec * 1000000 + end.tv_usec)-(start.tv_sec * 1000000 + start.tv_usec)), "ms");
}
Upvotes: 0
Views: 80
Reputation: 1772
Your problem is that all exec()
family functions expect only the executable name as the first parameter (without any arguments). The arguments are then passed according to the exec
function you decided to call. In the case of execlp()
, all the arguments (including the executable name) are passed as a null-terminated list.
Essentially, you want to call your function in this way:
execlp ("ls", "ls", "-l", (char *) 0);
The way to do this is by splitting the input
string on the space character (using strtok()
) and saving the results in different variables.
If you would like to handle however cases of multiple arguments, then you cannot achieve it by using execlp()
. Use execvp()
instead with the according modifications. You can find the man page for all exec()
functions here which will give you enough information.
Upvotes: 2