3.5作业

本文详细介绍了如何使用C语言编写代码,包括`write`和`read`操作来实现非递归文件夹拷贝,以及使用`fork`和循环创建一条包含100个进程的进程链,确保程序稳定性。
摘要由CSDN通过智能技术生成

作业1: 1:使用write 和 read 实现 文件夹拷贝功能,不考虑递归拷贝

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <dirent.h>
#include <sys/stat.h>

#define BUFFER_SIZE 1024

void copy_file(const char *src, const char *dest) {
    int src_fd = open(src, O_RDONLY);
    if (src_fd == -1) {
        perror("打开源文件失败");
        exit(1);
    }

    int dest_fd = open(dest, O_WRONLY | O_CREAT | O_TRUNC, 0644);
    if (dest_fd == -1) {
        perror("打开目标文件失败");
        exit(1);
    }

    char buffer[BUFFER_SIZE];
    ssize_t bytes_read;

    while ((bytes_read = read(src_fd, buffer, BUFFER_SIZE)) > 0) {
        if (write(dest_fd, buffer, bytes_read) != bytes_read) {
            perror("write");
            exit(1);
        }
    }

    if (bytes_read == -1) {
        perror("read");
        exit(1);
    }

    close(src_fd);
    close(dest_fd);
}

int main(int argc, char *argv[]) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <source_dir> <destination_dir>\n", argv[0]);
        exit(1);
    }

    DIR *dir = opendir(argv[1]);
    if (!dir) {
        perror("opendir");
        exit(1);
    }

    struct dirent *entry;
    while ((entry = readdir(dir)) != NULL) {
        if (entry->d_type == DT_REG) {
            char src_path[256];
            char dest_path[256];
            snprintf(src_path, sizeof(src_path), "%s/%s", argv[1], entry->d_name);
            snprintf(dest_path, sizeof(dest_path), "%s/%s", argv[2], entry->d_name);
            copy_file(src_path, dest_path);
        }
    }

    closedir(dir);

    return 0;
}
 

作业2: 使用循环+fork的形式。创建一条进程链,链条上总共有100个进程 要求:程序不崩溃

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main() 
{
    for (int i = 0; i < 100; i++) {
     int   res = fork();

        if (res < 0) {
            perror("fork failed");
            return 1;
        } else if (res == 0) {
            printf("第 %d层的子进程PID是 %d, 它的父进程PID是 %d\n", i+1, getpid(), getppid());
        } else {
            wait(NULL); 
            break;  
        }
    }

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值