jiankeabcd 2017-07-09 02:34 采纳率: 73.9%
浏览 2023
已采纳

使用C语言实现Linux管道符命令

例如
uniq < tmp.txt | wc -l
其中 tmp.txt为
0
0
1
1
1
2
0
2

可以使用fork, exec族群, pipe, dup, dup2, open, close的系统调用
不能直接使用execlp执行上述命令
我的想法是利用pipe实现单向管道,父进程使用exec执行uniq < txt,
执行后为
0
1
2
0
2
并将此标准输出用dup2替换为标准输入,进入子进程。子进程执行wc -l之后利用父进程的标准输入得到结果5
自己写的代码如下 但是无法正确输出 望高人解答

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>

int main(int argc, char const *argv[]){
  int fd[2];
  pid_t pid;
  pipe(fd);
  if((pid = fork()) == 0){/* child process */
    close(fd[1]);
    execlp("wc", "wc", "-l", "fd[1]", NULL);
    close(fd[0]);
  }
  else{/* parent process */
    close(fd[0]);
        dup2(0, 1);
        close(0);
    fd[1] = open("tmp.txt", O_RDONLY);
    execlp("uniq", "uniq", "tmp.txt", NULL);
    close(fd[1]);
  }
}
  • 写回答

1条回答 默认 最新

  • devmiao 2017-07-09 12:45
    关注
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试