linux文件拷贝(进程方法)
2017-03-15 19:34
211 查看
文件拷贝,父进程拷贝该文件的前一半,子进程拷贝后一半
/*************************************************************************
> 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);
}
相关文章推荐
- linux 拷贝文件方法
- 将文件从一台linux机器拷贝到多台的方法
- Linux--多进程拷贝一个文件
- linux下多进程的文件拷贝与进程相关的一些基础知识
- 【Linux】利用管道在进程通讯拷贝文件
- linux文件拷贝常用方法
- win7中将文件拷贝到虚拟机linux下的方法
- linux下scp远程拷贝包含空格的目录或者文件的解决方法
- Linux系统下不同机器之间拷贝文件的方法
- Linux默认允许单进程打开文件数量限制测试与修改方法
- win7中将文件拷贝到虚拟机linux下的方法
- 简单介绍Linux进程文件路径的获取方法
- 跟踪Linux进程打开文件数和解决方法
- Linux下查看进程打开的文件句柄数和如何修改方法
- Linux系统下不同机器之间拷贝文件的方法
- win7中将文件拷贝到虚拟机linux下的方法
- 将文件从一台linux机器拷贝到多台的方法
- 拷贝文件:linux--〉windows-->linux,丢失文件权限解决方法
- 【转】Linux系统下不同机器之间拷贝文件的方法
- 解读Linux系统文件权限的设置方法