ls | wc命令: 使用ls | wc,我们可以计算当前目录中所有文件的新行、单词和字母。我们可以从下面的代码执行后得到相同的结果。
null
方法: 首先,我们必须使用管道在阵列上进行进程间通信,其中[0]用于读取,[1]用于写入。我们可以用fork复制这个过程。在父进程中,标准输出是关闭的,因此ls命令的输出将转到[0],类似地,标准输入在子进程中也是关闭的。现在,如果我们运行程序输出将与linux ls | wc的命令相同。
以下是上述方法的实施情况:
// C code to implement ls | wc command #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include<errno.h> #include<sys/wait.h> #include <unistd.h> int main(){ // array of 2 size a[0] is for // reading and a[1] is for // writing over a pipe int a[2]; // using pipe for inter // process communication pipe(a); if (!fork()) { // closing normal stdout close(1); // making stdout same as a[1] dup(a[1]); // closing reading part of pipe // we don't need of it at this time close(a[0]); // executing ls execlp( "ls" , "ls" ,NULL); } else { // closing normal stdin close(0); // making stdin same as a[0] dup(a[0]); // closing writing part in parent, // we don't need of it at this time close(a[1]); // executing wc execlp( "wc" , "wc" ,NULL); } } |
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END