Program:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main()
{
int cpid=fork();
if(cpid==0){
execl("/bin/ls","ls","-lah","--color",NULL);
}
else{
int status;
waitpid(cpid,&status,0);
if(status!=0)
printf("Error Occured\n");
}
return 0;
}
Output:
$ ./a.out
total 20K
drwxrwxr-x 1 guest guest 4.0K Jan 12 15:21 .
drwxrwxr-x 1 guest guest 4.0K Jan 12 15:21 ..
-rwxrwxr-x 1 guest guest 7.2K Jan 12 15:19 a.out
-rw-rw-r-- 1 guest guest 372 Jan 12 15:20 execl.c
$
In the above program, parent create a child and the child execute the ls command. But, my requirement is to save the output of ls in an array in parent. Is there any way to do this.
exec*()
family functions replace the current process's image with new one. So you can't read it directly. You don't need a child process to read the output from an external command. You can use popen()
to achieve that.
If you do have to create a child process, then you can use pipe(2)
to read from the output from the child process. You can find a simple example on the linked man page.