01父子进程利用管道实现cp工具

思路:

创建管道,fork;然后在父进程中用fget从源文件中读取内容,然后写到管道;子进程从管道中读取内容,然后写入到目标文件

实现:

/***target : use fgets() and write() to copy files
 *  main points : pipe() fork()
 */
#include <sys/types.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>

#define READBLOCK 1024
int main(int argc, char *argv[]) { FILE* sfp; int fd; char opt; int wp[2]; if(argc < 2){ printf("Usage:\n fcp [OPTION] SOURCE DEST\n"); printf("OPTION: -r copy directories recursively\n"); abort(); }else if(argc == 3){ sfp = fopen(argv[1], "r"); fd = open(argv[2], O_CREAT | O_WRONLY | O_APPEND, 0666); }else if(argc == 4 && *argv[1] == 'r'){ opt = *argv[1]; sfp = fopen(argv[2], "r"); fd = open(argv[2], O_CREAT | O_WRONLY | O_APPEND, 0666); } if(!sfp || (fd < 0)) { printf("open error, errno: %d\n", errno); return 1; } pipe(wp); char buffer[READBLOCK]; pid_t pid = fork(); if(pid > 0) { close(wp[0]); FILE *wf = fdopen(wp[1], "w"); size_t nread = 0, nwrite = 0; while(fgets(buffer, READBLOCK, sfp) != NULL) { nread = strlen(buffer); write(wp[1], buffer, nread); } close(wp[1]); if(waitpid(pid, NULL, 0) < 0) printf("waitpid error\n"); fclose(sfp); close(fd); exit(0); } else if( pid == 0) { close(wp[1]); FILE* rf = fdopen(wp[0], "r"); size_t nread = 0, nwrite = 0; while(fgets(buffer, READBLOCK, rf) != NULL) { nread = strlen(buffer); write(fd, buffer, nread); memset(buffer, '\0', READBLOCK); } } }

理想是美好的,现实却是,利用父子进程通过管道实现cp工具就是一坨屎
Smile
,性能差得不行。
$ time cp file.0 tf1
real    0m6.077s
user    0m0.013s
sys    0m3.176s
$ time ./fcpv2 file.0 tf4
real	2m23.157s
user	0m17.228s
sys	2m38.983s

 



 

posted @ 2022-05-14 11:16  桃花春风一杯酒  阅读(57)  评论(0)    收藏  举报