【Linux~有名管道间实现cat功能~服务端,客户端收发文件】

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
实现命令cat功能,我们可以编写两个程序,一个程序作为父进程,另一个程序作为子进程,通过无名管道进行通信。 以下是父进程的代码: ``` #include <stdlib.h> #include <stdio.h> #include <unistd.h> #include <string.h> int main() { int fd[2]; pid_t pid; char buf[1024]; if (pipe(fd) < 0) { perror("pipe error"); exit(1); } if ((pid = fork()) < 0) { perror("fork error"); exit(1); } else if (pid > 0) { /* parent process */ close(fd[0]); /* close read end */ while (fgets(buf, sizeof(buf), stdin) != NULL) { int len = strlen(buf); if (write(fd[1], buf, len) != len) { perror("write error"); exit(1); } } close(fd[1]); /* close write end */ wait(NULL); } else { /* child process */ close(fd[1]); /* close write end */ if (dup2(fd[0], STDIN_FILENO) != STDIN_FILENO) { perror("dup2 error"); exit(1); } close(fd[0]); /* close read end */ execlp("cat", "cat", NULL); perror("execlp error"); exit(1); } return 0; } ``` 父进程从标准输入中读取数据,然后将数据写入到无名管道中,最后关闭写端。子进程从无名管道中读取数据,并通过标准输出将数据输出出来。 编译运行程序: ``` $ gcc pipe_cat.c -o pipe_cat $ echo "Hello, world!" | ./pipe_cat Hello, world! ``` 这里使用了echo命令将字符串"Hello, world!"写入到标准输入中,并通过管道传递给pipe_cat程序。最后,程序输出了"Hello, world!"。由于子进程是通过execlp函数来执行cat命令的,因此这个程序可以实现cat命令的所有功能
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值