功能:
父进程创建一个子进程父进程负责读用户终端输入,并写入管道
子进程从管道接收字符流写入另一个文件
代码:
#include <stdio.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <stdlib.h> #include <fcntl.h> #define MAX 100 int main() { int n,c = 0; int fd[2]; char ch; pid_t pid; char buffer[MAX+10]; if(pipe(fd) < 0) { //创建管道 puts("管道创建失败"); exit(1); } pid = fork(); //创建子进程 if(pid < 0) puts("子进程创建失败"); else if(pid > 0) { //父 close(fd[0]); //关闭读端口 puts("please input what you want to say:"); while((ch = getchar()) != ‘\n‘) { //读字符串(可空格)到buffer if(c == MAX) { puts("buffer is fulled!"); break; } buffer[c++] = ch; } buffer[c] = ‘\0‘; write(fd[1], buffer, c); //写入管道 } else { //子 close(fd[1]); //关闭写端口 n = read(fd[0], buffer, MAX); //从管道中读出数据,n为读出的字符个数 printf("What you input is: [/home/whatbeg/hq/oshomework.txt]\n"); int dft_fd = open("/home/whatbeg/hq/oshomework.txt", O_RDWR | O_CREAT, 0777); //打开文件,如果没有,创建一个对三方都可读可写可执行的txt文件 if(dft_fd == -1) { //打开失败 puts("打开文件失败!\n"); exit(1); } write(STDOUT_FILENO, buffer, n); //写到终端,方便观测 write(dft_fd, buffer, n); //写到文件 close(dft_fd); //关闭文件 } return 0; } // ‘gets‘ is deprecated //警告: the ‘gets‘ function is dangerous and should not be used.
运行结果如下:
时间: 2024-10-22 11:23:20