8.26 进程

作业:创建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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值