作业:创建3个进程,子进1程拷贝文件的前一半,子进程2拷贝后一半文件,父进程回收两个子进程资源。
#include <myhead.h>
int main(int argc, char const *argv[])
{
ssize_t read1, write1;
char buff[1024];
pid_t pid1 = fork();
if (pid1 == 0)
{
int fd1 = open("1.txt", O_RDONLY);
if (fd1 == -1)
{
perror("open 1");
return -1;
}
off_t file_max = lseek(fd1, 0, SEEK_END);
off_t file_mid = file_max / 2;
int fd2 = open("2.txt", O_CREAT | O_TRUNC | O_RDWR, 0664);
if (fd2 == -1)
{
perror("open 2");
return -1;
}
lseek(fd1, 0, SEEK_SET);
off_t temp = file_mid;
while (temp > 0 && (read1 = read(fd1, buff, sizeof(buff))) > 0)
{
if (read1 > temp)
{
read1 = temp;
}
write1 = write(fd2, buff, read1);
temp -= write1;
}
close(fd1);
close(fd2);
exit(EXIT_SUCCESS);
}
else if (pid1 > 0)
{
pid_t pid2 = fork();
usleep(1);
if (pid2 == 0)
{
int fd1 = open("1.txt", O_RDONLY);
if (fd1 == -1)
{
perror("open 1.txt");
return -1;
}
off_t file_max = lseek(fd1, 0, SEEK_END);
off_t file_mid = file_max / 2;
int fd2 = open("2.txt", O_WRONLY | O_APPEND);
if (fd2 == -1)
{
perror("open 2.txt");
return -1;
}
off_t temp = file_max - file_mid;
lseek(fd1, file_mid, SEEK_SET);
while (temp > 0 && (read1 = read(fd1, buff, sizeof(buff))) > 0)
{
if (read1 > temp)
{
read1 = temp;
}
write1 = write(fd2, buff, read1);
temp -= write1;
}
close(fd1);
close(fd2);
exit(EXIT_SUCCESS);
}
else if (pid2 > 0)
{
wait(NULL);
wait(NULL);
}
else
{
perror("fork");
return -1;
}
}
else
{
perror("fork");
return -1;
}
return 0;
}