首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用cat和execvp

使用cat和execvp
EN

Stack Overflow用户
提问于 2017-02-09 01:09:59
回答 1查看 1K关注 0票数 0

我试图理解为什么在C中使用cat命令的这段代码不能与execvp一起使用。

代码语言:javascript
复制
char *in[5] ={"cat", "file1.txt", ">>", "file2.txt", 0};
execvp(in[0], in);

当我运行它时,它显示file1.txt的内容,但随后显示:

cat:>>没有这样的文件或目录。

然后显示file2.txt的内容,为什么它不能识别这种情况下的>>操作符?

EN

回答 1

Stack Overflow用户

发布于 2017-07-05 21:22:34

您可以读取"man tee“命令,该命令从标准输入读取,并写入标准输出和文件。你可以用下面的例子实现这一点。

代码语言:javascript
复制
#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;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42119440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档