转换cat file.txt | wc -l程序代码c

时间:2016-12-27 14:59:22

标签: c linux

我是管道的新手,我想开发一个程序来理解和了解这个。我的想法是使用c将命令shell cat传递给wc。我正在做一个非常简单的程序,它使用一个退出文件(例如test.txt),但目前我只能显示内容。我只想要计算大约1个特定文件的行数。

这可以实现吗?或许我必须做另一种选择?这是我的基本代码:

int main(int argc, char *argv[]) {
    pid_t pid;
    int fd[2];

    pipe(fd);
    pid = fork();

    if (pid == -1) {
        perror("fork");
        exit(1);    
    }

    if (pid == 0) {
        /* Child process closes up input side of pipe */
        close(fd[0]);
        execlp("cat", "cat", "test.txt", NULL);
        //I don't know how communicate this process with the other process
    } else {
        /* Parent process closes up output side of pipe */
        close(fd[1]);
        execlp("wc", "wc", "-l", NULL);
    }
}

2 个答案:

答案 0 :(得分:2)

在调用execlp()之前,您必须将管道的相应末端重定向到标准输入和/或标准输出。如果此调用成功,则当前进程已替换为新进程,不会执行其他代码,但如果失败,则应使用perror()进行投诉。

以下是代码的更正版本:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main (int argc, char *argv[]) {
    pid_t pid;
    int fd[2];

    if (pipe(fd)) {
        perror("pipe");
        return 1;
    }

    pid = fork();
    if (pid == -1) {
        perror("fork");
        return 1;
    }

    if (pid == 0) {
        /* Child process redirects its output to the pipe */
        dup2(fd[1], 1);
        close(fd[0]);
        close(fd[1]);
        execlp("cat", "cat", "test.txt", NULL);
        perror("exec cat");
        return 1;
    } else {
        /* Parent process redirects its input from the pipe */
        dup2(fd[0], 0);
        close(fd[0]);
        close(fd[1]);
        execlp("wc", "wc", "-l", NULL);
        perror("exec wc");
        return 1;
    }
}

答案 1 :(得分:0)

如果你只关心文件中的行数,你可以使用popen运行整个命令,然后读输出输出或任何错误

e.g. fd = popen("cat test.txt | wc -l", "r");

然后使用read方法读取输出。您还可以使用pclose(fd)的返回值来检查流程是否成功完成。