文件拷贝,父进程拷贝该文件的前一半,子进程拷贝后一半
/*************************************************************************
> 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);
}