2024.1.4 IO进程线程 作业

思维导图

练习题

1> 创建出三个进程完成两个文件之间拷贝工作,子进程1拷贝前一半内容,子进程2拷贝后一半内容,父进程回收子进程的资源

#include <myhead.h>

int main(int argc, char const *argv[])
{
    //读取原文件计算个数
    int file = open("./test.txt", O_RDONLY);
    //打开写入的文件
    int file2 = open("./output.txt", O_WRONLY | O_TRUNC | O_CREAT, 0664);
    if (file == -1 || file2 == -1)
    {
        perror("文件打开失败");
        return -1;
    }

    //start 文件开头,end 文件字符个数
    off_t start = 0;
    off_t end = lseek(file, 0, SEEK_END);
    //判断内容读取到一半,写入一半
    end = end / 2;
    //将光标定位到开头
    lseek(file, 0, SEEK_SET);
    //搬运工
    char buffer[1] = "";
    ssize_t bytes_read, bytes_written;

    //子线程1 完成前半段拷贝
    pid_t pid1 = fork();
    //子线程2 完成后半段拷贝
    pid_t pid2 = fork();
    //子进程创建成功后写入一半
    if (pid1 == 0)
    {
        while (start < end)
        {
            bytes_read = read(file, buffer, sizeof(buffer));
            if (bytes_read <= 0)
                break;
            bytes_written = write(file2, buffer, bytes_read);
            //start往后偏移
            start += bytes_written;
        }
        puts("前半段拷贝完成");
        exit(0);
    }

    //子进程创建成功后写入一半
    if (pid2 == 0)
    {
        //重新确定start和end位置
        start = end;
        end = lseek(file, end, SEEK_END);
        while (start < end)
        {
            bytes_read = read(file, buffer, sizeof(buffer));
            if (bytes_read <= 0)
                break;
            bytes_written = write(file2, buffer, bytes_read);
            //start往后偏移
            start += bytes_written;
        }
        puts("后半段拷贝完成");
        exit(0);
    }

    //回收子线程pid1
    waitpid(pid1, NULL, 0);
    //回收子线程pid2
    waitpid(pid2, NULL, 0);

    close(file);
    close(file2);

    return 0;
}

  • 9
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值