I'm writing a program in C that reads from a file (e.g a file called ffff in the same folder of my .c source file): this files contains two command:
ls -l
tac
My program open this file, reads the commands and the relative arguments and by using a pipe shows me the same output of
ls -l | tac
I have used the get line and I have thought to use execvp
but the output is
execvp error: No such file or directory.
Can you help me? This is my code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <error.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char *argv[])
{
int mypipe[2];
FILE *stream;
char *line=NULL;
size_t len=0;
ssize_t read;
/*controllo il numero degli argomenti passati*/
if(argc != 2){
fprintf(stderr, "no such arguments \n");
exit(1);
}
/*apro il file in sola lettura*/
stream=fopen(argv[1], "r");
if(stream==NULL){
exit(EXIT_FAILURE);
}
/*apro la pipe*/
if(pipe(mypipe) == -1){
fprintf(stderr, "Error pipe\n");
exit (1);
}
if(fork()==0){
close(1); /*chiudo lo stdout*/
dup(mypipe[1]); /*rimpiazzo lo stdout con la pipe*/
close(mypipe[0]); /*chiudo la read della pipe*/
close(mypipe[1]);
read=getline(&line, &len, stream);
execvp(argv[1], &line);
perror("execvp failed");
exit (1);
}
if(fork()==0){
close(0); /*chiudo lo stdin*/
dup(mypipe[0]); /*rimpiazzo lo stdin con la pipe read*/
close(mypipe[1]); /*chiudo la write della pipe*/
close(mypipe[0]);
read=getline(&line, &len, stream);
execvp(argv[1], &line);
perror("execvp 2 failed");
exit (1);
}
close(mypipe[0]);
close(mypipe[1]);
wait(0);
wait(0);
free(line);
fclose(stream);
exit (0);
}