2017-02-08 4 views
0

Пытаясь понять, почему этот раздел кода с помощью команды кошки не работает с execvp в С.Использование кота и execvp

char *in[5] ={"cat", "file1.txt", ">>", "file2.txt", 0}; 
execvp(in[0], in); 

При запуске он отображает содержимое file1.txt, но потом говорит:

cat: >> Нет такого файла или каталога.

Затем отображает содержимое файла file2.txt Почему бы ему не распознать оператор >> в этом случае?

ответ

0

Вы можете прочитать команду «man tee», которую она считывает со стандартного ввода и записывает в стандартный вывод и файлы. Вы можете добиться этого ниже.

#include <sys/types.h> 
#include <sys/wait.h> 
#include <signal.h> 
#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 
#include <unistd.h> 
#include <errno.h> 

/* 
Implementation of below command: 
cat file1.txt > file2.txt 
*/ 

char *cmd1[] = { "/bin/cat", "file1.txt", 0 }; 
char *cmd2[] = { "tee", "file2.txt", 0 }; 

static void sigchld_hdl (int sig) 
{ 
    int status; 
    while (waitpid(-1, &status, 0) > 0) {  
     if(WIFEXITED(status)) 
      printf("Child exited with code %d\n", WEXITSTATUS(status)); } 
} 

int runcmd(int pfd[]) 
{ 
    int i=0; 

    switch (fork()) { 
     case -1: 
      perror ("fork"); 
      return 1; 
     case 0: 
      dup2(pfd[0], 0); 
      close(pfd[1]); /* the child does not need this end of the pipe */ 
      execvp(cmd2[0], cmd2); 
      perror(cmd2[0]); 
      exit(10); 
     default: /* parent */    
      dup2(pfd[1], 1); 
      close(pfd[0]); /* the parent does not need this end of the pipe */ 
      execvp(cmd1[0], cmd1); 
      perror(cmd1[0]); 

    } 
    sleep(1); 
} 

int main (int argc, char *argv[]) 
{ 
    struct sigaction act; 
    int fd[2]; 

    pipe(fd); 

    memset (&act, 0, sizeof(act)); 
    act.sa_handler = sigchld_hdl; 

    if (sigaction(SIGCHLD, &act, 0)) { 
     perror ("sigaction"); 
     return 1; 
    } 
    runcmd(fd); 

    return 0; 
} 
Смежные вопросы