linux文件拷贝(进程方法)

56 篇文章 2 订阅

生气文件拷贝,父进程拷贝该文件的前一半,子进程拷贝后一半

/*************************************************************************
	> File Name: work.c
	> Author: XXDK
	> Email: v.manstein@qq.com 
	> Created Time: Wed 15 Mar 2017 01:41:55 AM PDT
 ************************************************************************/

#include<stdio.h>
#include<sys/stat.h>
#include<unistd.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<fcntl.h>

int main(int argc, const char *argv[])
{
	char buf[32] = {0};
	int fsrc, fdest;
	int file_len = 0;
	int file_len_half = 0;
	int ret = 0;
	int count = 0;
	int count_rmd = 0;
	pid_t pid;

	if(argc < 3) {
		perror("wokao");
		exit(-1);
	}

	fsrc = open(argv[1], O_RDONLY);
	if(fsrc < 0) {
		perror("open src error");
		exit(-1);
	}
	fdest = open(argv[2], O_CREAT|O_WRONLY|O_TRUNC);
	if(fdest < 0) {
		close(fsrc);
		perror("open dest error");
		exit(-1);
	}
	printf("ready!\n");

	file_len = lseek(fsrc, 0, SEEK_END);
	file_len_half = file_len / 2;

	count_rmd = file_len_half % sizeof(buf);// 计算最后一次拷贝几个字节
	count = file_len_half / sizeof(buf);	// 计算需要拷贝多少个32次

	printf("file length: %d bytes, file half lenght: %d\n", file_len, file_len/2);
	//-----------------------------------------------------------------------------
	if((pid = fork()) == 0) {// child process
		int i;
		lseek(fdest, file_len_half, SEEK_SET);
		lseek(fsrc, file_len_half, SEEK_SET);
		while(1) {

			ret = read(fsrc, buf, sizeof(buf));
			i++;
			
			if(count == i) {
				ret = read(fsrc, buf, count_rmd);
			}
			write(fdest, buf, ret);
			if(count == i)
				break;
		}
		close(fdest);
		close(fsrc);
	} else if(pid > 0) { // parent process
		int i = 0;
		lseek(fsrc, 0, SEEK_SET);
		while(1) {
			ret = read(fsrc, buf, sizeof(buf));
			i++;
			
			if(count == i) {
				ret = read(fsrc, buf, count_rmd);
			}
			write(fdest, buf, ret);
			if(count == i)
				break;
		}
		waitpid(-1, NULL, 0);
	} else {
		perror("fuck error");
		close(fdest);
		close(fsrc);
		exit(-1);
	}

	exit(0);
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值