qfedu-linux-advanced-level/day4/homework/h5.c

60 lines
1.5 KiB
C
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 创建一个父进程和一个子进程,父进程从文件读取数据,并通过管道发送给子进程,子进程将数据输出到标准输出。
// 例如父进程从文件读取到的数据为hello world子进程将输出hello world
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <fcntl.h>
int main()
{
pid_t pid;
int fd[2];
int f = pipe(fd);
if (f == -1)
{
perror("pipe"); // 创建管道失败
_exit(1); // 创建管道失败,退出
}
pid = fork();
if (pid == 0)
{
close(fd[1]); // 子进程关闭管道写端
char buf[32] = "";
int len = read(fd[0], buf, sizeof(buf));
// buf[len] = '\0'; // 不加'\0',父进程读取到的数据会有乱码
printf("子进程收到父进程数据: %s", buf);
close(fd[0]); // 关闭管道读端
_exit(0); // 子进程退出
}
close(fd[0]); // 父进程关闭管道读端
int fd_file = open("a.txt", O_RDONLY); // 打开文件
if (fd_file == -1)
{
perror("open");
_exit(1);
}
char buf[32] = "";
int len = read(fd_file, buf, sizeof(buf));
if (len == -1)
{
perror("read");
_exit(1);
}
// 不加'\0',子进程读取到的数据会有乱码
write(fd[1], buf, strlen(buf) /* + 1 */); // 包括'\0' , 写入管道
close(fd[1]); // 关闭管道写端
close(fd_file);
waitpid(0, NULL, 0); // 等待子进程退出
return 0;
}