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");
}
ls -l, not a program calledlswith an argument of-l.(char *)0instead ofNULL? I mean, the C standard dictates that 0 (of any kind) and NULL will be evaluated the same, but I just find it to be a somewhat disputable practice.scanf (" %[^\n]s", input);This is expecting a literal 's' in the inputstdinNot what you want. Suggest:if( scanf( " %[^\n]", input ) != 1 ) { //handle error and exit }if (pid == 0){ ChildProcess (); } else { wait (NULL); ParentProcess ();this, whenfork()fails, will callwait()with no child process. This is a problem that you need to fix. Suggest using:switch( pid ) { case -1: perror( "fork failed: ); exit( EXIT_FAILURE ); break; case 0: ChildProcess(); break; default: wait(); ParentProcess(); break; }