父进程子进程各拷贝1/2
#include<myhead.h>
int main()
{
int fd_r = open("./fopen.txt", O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
int fd_w = open("./fopen1.txt", O_WRONLY | O_CREAT | O_TRUNC, 0664);
if(fd_w < 0)
{
perror("open");
return -1;
}
off_t file_size = lseek(fd_r, 0, SEEK_END);
printf("文件的大小是%ld字节\n", file_size);
pid_t cpid = fork();
if(cpid > 0)
{
wait(NULL);
lseek(fd_r, 0, SEEK_SET);
lseek(fd_w, 0, SEEK_SET);
char buf;
for(int i = 0; i < file_size/2; i++)
{
if(read(fd_r, &buf, 1) < 0)
{
perror("read");
return -1;
}
if(write(fd_w, &buf, 1) < 0)
{
perror("write");
return -1;
}
}
}
else if(cpid == 0)
{
lseek(fd_r, file_size/2, SEEK_SET);
lseek(fd_w, file_size/2, SEEK_SET);
char buf;
for(int i = file_size/2; i < file_size; i++)
{
if(read(fd_r, &buf, 1) < 0)
{
perror("read");
return -1;
}
if(write(fd_w, &buf, 1) < 0)
{
perror("write");
return -1;
}
}
}
else
{
perror("fork");
return -1;
}
close(fd_r);
close(fd_w);
return 0;
}
父进程和两个子进程各拷贝1/3
#include<myhead.h>
int main(int argc, const char *argv[])
{
int fd_r = open("./fopen.txt", O_RDONLY);
if(fd_r < 0)
{
perror("open");
return -1;
}
int fd_w = open("./fopen1.txt", O_WRONLY | O_CREAT | O_TRUNC, 0664);
if(fd_w < 0)
{
perror("open");
return -1;
}
off_t file_size = lseek(fd_r, 0, SEEK_END);
printf("文件的大小是%ld字节\n", file_size);
pid_t cpid = fork();
if(cpid > 0)
{
wait(NULL);
pid_t c2pid = fork();
if(c2pid > 0)
{
wait(NULL);
char buf;
for(int i = file_size - file_size/3; i < file_size; i++)
{
if(read(fd_r, &buf, 1) < 0)
{
perror("read");
return -1;
}
if(write(fd_w, &buf, 1) < 0)
{
perror("write");
return -1;
}
}
}
else if(c2pid == 0)
{
char buf;
for(int i = file_size/3; i < file_size - file_size/3; i++)
{
if(read(fd_r, &buf, 1) < 0)
{
perror("read");
return -1;
}
if(write(fd_w, &buf, 1) < 0)
{
perror("read");
return -1;
}
}
}
else
{
perror("fork");
return -1;
}
}
else if(cpid == 0)
{
lseek(fd_r, 0, SEEK_SET);
lseek(fd_w, 0, SEEK_SET);
char buf;
for(int i = 0; i < file_size/3; i++)
{
if(read(fd_r, &buf, 1) < 0)
{
perror("read");
return -1;
}
if(write(fd_w, &buf, 1) < 0)
{
perror("write");
return -1;
}
}
}
else
{
perror("fork");
return -1;
}
close(fd_r);
close(fd_w);
return 0;
}