[英]Transform cat file.txt | wc -l program code c
我是管道的新手,我想开发一个小程序来了解和了解这一点。 我的想法包括使用c将命令外壳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);
}
}
您必须在调用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;
}
}
如果您只关心文件中的行数,则可以使用popen运行整个命令,然后读取输出以获取输出或任何错误
e.g. fd = popen("cat test.txt | wc -l", "r");
然后使用read
方法读取输出。 您还可以使用pclose(fd)
返回值来检查进程是否成功完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.