简体   繁体   English

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

[英]Transform cat file.txt | wc -l program code c

I'm very newbie about pipes and I want develop a little program for understand and learn about this. 我是管道的新手,我想开发一个小程序来了解和了解这一点。 My idea consist to communicate command shell cat to wc using c. 我的想法包括使用c将命令外壳cat传达给wc。 I was doing a very simple program that use an exiting file (test.txt for example) but for the moment I can only display the content. 我当时在做一个非常简单的程序,使用的是现有文件(例如test.txt),但目前我只能显示内容。 I only want count the number of lines about 1 specific file. 我只想计算大约1个特定文件的行数。

Is this possible to implement? 这可能实现吗? Or maybe I must do another option? 或者也许我必须做另一种选择? Here my basic code: 这是我的基本代码:

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);
    }
}

You must redirect the appropriate end of the pipe to standard input and/or standard output before the call to execlp() . 您必须在调用execlp()之前将管道的适当一端重定向到标准输入和/或标准输出。 If this call succeeds, the current process has been replaced with the new one, no further code is executed, but if it fails, you should complain with a perror() . 如果此调用成功,则当前进程已被新进程替换,不再执行任何代码,但是,如果失败,则应使用perror()投诉。

Here is a corrected version of the code: 这是代码的更正版本:

#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;
    }
}

if you only care about the number of lines in the file you can just run the entire command using popen and then read the output for output or any error 如果您只关心文件中的行数,则可以使用popen运行整个命令,然后读取输出以获取输出或任何错误

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

then use read method to read the output. 然后使用read方法读取输出。 you can also use return value from pclose(fd) to check if process completed successfully. 您还可以使用pclose(fd)返回值来检查进程是否成功完成。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM