2024.02.20作业

1. 使用多进程完成两个文件的拷贝,父进程拷贝前一半,子进程拷贝后一半,父进程回收子进程的资源

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

#define MAXSIZE 1024

int main(int argc, char const *argv[])
{
    pid_t pid = fork();
    if (0 == pid)
    {
        usleep(100000);
    }

    // 区分父子进程打开 dest 的方式
    int src = -1, dest = -1;
    src = open("pm.bmp", O_RDONLY);
    if (0 != pid)
    {
        dest = open("pm2.bmp", O_WRONLY|O_CREAT|O_TRUNC, 0664);
    }
    else
    {
        dest = open("pm2.bmp", O_RDWR|O_APPEND|O_CREAT);
    }
    if (-1 == src || -1 == dest)
    {
        perror("open error");
        return -1;
    }

    // timer
    struct timespec start_time = { 0, 0 }, end_time = { 0, 0 };
    timespec_get(&start_time, TIME_UTC);

    // 计算文件长度,控制光标位置
    int file_len = lseek(src, 0, SEEK_END);
    lseek(src, 0, SEEK_SET);
    if (0 == pid)
    {
        lseek(src, file_len / 2, SEEK_SET);
        lseek(dest, file_len / 2, SEEK_SET);
    }

    // 复制
    int len = 0, count = 0;
    char buf[MAXSIZE];
    int bufsize = sizeof(buf);
    while (count < file_len / 2)
    {
        if (file_len / 2 - count < bufsize)
        {
            bufsize = file_len / 2 - count;
        }

        len = read(src, buf, bufsize);
        write(dest, buf, len);
        count += sizeof(buf);
    }
    
    // timer,计算复制所用时间 (ns)
    timespec_get(&end_time, TIME_UTC);
    printf("pid:%d, time:%ld\n", pid, end_time.tv_nsec - start_time.tv_nsec);

    if (0 == pid)
    {
        exit(0);
    }

    // 等待回收子进程资源
    wait(NULL);

    close(src);
    close(dest);

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值