使用父子进程完成两个文件的拷贝,父进程拷贝前一半,子进程拷贝后一半,两个进程同时进行
#include <myhead.h>
int main(int argc, const char *argv[])
{//用于保存pid号pid_t pid = -1;//创建子进程pid = fork();//打印一下进程号printf("pid=%d\n",pid);//判断3个文件是否传输成功if(argc != 3){printf("input file error:\n");return -1;}//打开源文件FILE * sfp = fopen(argv[1],"r");if(sfp == NULL){perror("fopen error");return -1;}//计算源文件的大小用以确定光标位置fseek(sfp, 0 ,SEEK_END);int len = ftell(sfp);printf("len=%d\n",len);rewind(sfp); if(pid > 0) //当前进程{ //打开目标文件FILE * dfp = fopen(argv[2],"w");if(dfp == NULL){perror("fopen error");return -1;}//拷贝while(1){int res = fgetc(sfp);//读取到源文件一半停止int len1 = ftell(sfp);if(res == EOF || len1 == len/2){break;}fputc(res,dfp);}//关闭文件fclose(sfp);fclose(dfp);}else if(pid == 0) //子进程{ //打开目标文件FILE * dfp = fopen(argv[2],"a");if(dfp == NULL){perror("fopen error");return -1;}//移动光标到文件中间int len1 = len/2;fseek(sfp,len1-1,SEEK_SET);//拷贝while(1){int res = fgetc(sfp);// printf("res=%c\n",res);if(EOF == res){break;}fputc(res,dfp);}//刷新缓冲区fflush(dfp);//关闭文件fclose(sfp);fclose(dfp);}else //创建进程失败{printf("fork error\n");return -1;}return 0;
}