2016-12-23 1 views
2

J'essaye d'implémenter la commande cat en invoquant la fonction exec() et en en sauvegardant la sortie dans un fichier tmp. Mon problème est que je sais qu'après avoir invoqué exec() quoi que ce soit après sera ignoré, il n'y a donc aucun intérêt à boucler le exec().comment exec() dans une boucle for? en C

Si j'ai N nombre d'arguments à passer au programme principal, comment puis-je boucle exec() afin de lire tous les arguments?

Note: Utiliser system() n'est pas un choix pour moi, c'est comme ça que l'affectation est.

En ce moment j'ai le code suivant d'une manière pas très élégante:

#include <unistd.h> 
#include <stdio.h> 
#include <string.h> 
#include <fcntl.h> 
#include <stdlib.h> 
#include <time.h> 
#include <errno.h> 
#include <sys/stat.h> 
#include <sys/times.h> 
#include <sys/wait.h> 

int main(int argc,char *argv[]) 
{ 
    int fd; 
    char filename[] = "tmp.txt"; 

    fd = open(filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); 
    dup2(fd, 1); // make stdout go to file 
    dup2(fd, 2); // make stderr go to file     
    close(fd); 

    execl("/bin/cat", argv[0], argv[1], argv[2], argv[3], NULL); 

    return(0); 
} 
+0

-vous dire passer, pas analyser, non? –

+1

Et 'execv()' devrait faire exactement ce que vous voulez. https://linux.die.net/man/3/execv –

+0

@MarkYisri, vous avez raison, ma faute d'orthographe. – krm

Répondre

4

Vous recherchez execv (fonction standard):

int execv(const char *path, char *const argv[]); 

qui acceptera un argv. Pour la conformité standard, assurez-vous que argv[0] == path.

Alors, voici votre code, réécrite:

int main(int argc,char *argv[]) 
{ 
    int fd; 
    char filename[] = "tmp.txt"; 

    fd = open(filename, O_RDWR | O_CREAT, S_IRUSR | S_IWUSR); 
    dup2(fd, 1); // make stdout go to file 
    dup2(fd, 2); // make stderr go to file     
    close(fd); 
    execv("/bin/cat", (char *[]) { "/bin/cat", NULL }); 
    return(0); 
} 
+0

BINGO !!!! Je vous remercie!!! – krm