说明,父子进程不会相互干扰,即系统文件表不使用同一张即可。---》说明父进程开一次文件,子进程自己开一次文件。
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
//printf("%ld\n",size);
// 创建一个子进程
pid_t pid = fork();
// 根据pid判断
if(pid > 0) // 父进程
{
int fd_r = open("./1.png", O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
off_t size = lseek(fd_r, 0, SEEK_END);
int fd_w = open("./2.png", O_WRONLY|O_CREAT|O_TRUNC, 0777);
if(fd_w < 0)
{
perror("open_w");
return -1;
}
lseek(fd_r, 0, SEEK_SET);
lseek(fd_w, 0, SEEK_SET);
char c = 0;
int i = 0;
for(i=0; i<size/2; i++)
{
read(fd_r, &c, 1);
write(fd_w, &c, 1);
}
printf("文件前半部分拷贝完成\n");
close(fd_r);
close(fd_w);
}
else if(0 == pid) // 子进程
{
int fd_r = open("./1.png", O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
off_t size = lseek(fd_r, 0, SEEK_END);
int fd_w = open("./2.png", O_WRONLY|O_CREAT|O_TRUNC, 0777);
if(fd_w < 0)
{
perror("open_w");
return -1;
}
lseek(fd_r, size/2, SEEK_SET);
lseek(fd_w, size/2, SEEK_SET);
char c = 0;
int i = 0;
for(i=size/2; i<size; i++)
{
read(fd_r, &c, 1);
write(fd_w, &c, 1);
}
printf("文件后半部分拷贝完成\n");
close(fd_r);
close(fd_w);
}
else
{
perror("fork");
return -1;
}
return 0;
}
测试结果
文件前半部分拷贝完成
ubuntu@ubuntu:10.11$ 文件后半部分拷贝完成
ls -l
总用量 52
-rw-rw-r-- 1 ubuntu ubuntu 1392 十月 11 21:28 1.c
-rwxrw-rw- 1 ubuntu ubuntu 9853 十月 11 16:06 1.png
-rwxrwxr-x 1 ubuntu ubuntu 9853 十月 11 21:29 2.png
-rwxrwxr-x 1 ubuntu ubuntu 12744 十月 11 21:29 a.out
-rw-rw-r-- 1 ubuntu ubuntu 532 十月 11 16:06 fork.c
-rw-rw-r-- 1 ubuntu ubuntu 1088 十月 11 20:47 half_copy.c