9.8作业

利用文件IO函数拷贝图片。要求父进程拷贝前半部分,子进程拷贝后半部分。
#include 

int main(int argc, const char* argv[])
{
    // 打开文件
    int fd1 = open(argv[1], O_RDONLY);
    if (fd1 < 0)
        PRINT_ERR("open f1");
    int fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666);
    if (fd2 < 0)
        PRINT_ERR("open f2");

    // 获取要拷贝的文件大小
    const off_t size = lseek(fd1, 0, SEEK_END);
    lseek(fd1, 0, SEEK_SET);

    // 创建子进程
    pid_t pid = fork();

    // 父进程
    if (pid > 0) {
        char str[10];
        ssize_t res;
        while (1) {
            if (lseek(fd1, 0, SEEK_CUR) > size / 2) {
                puts("父进程拷贝结束!");
                break;
            }
            res = read(fd1, str, sizeof(str));
            write(fd2, str, res);
        }
        close(fd2);
        close(fd1);
        
        wait(NULL);
    }
    // 子进程
    else if (pid == 0) {
        //关闭原有的文件并重新打开
        close(fd2);
        close(fd1);
        int fd1 = open(argv[1], O_RDONLY);
        if (fd1 < 0)
            PRINT_ERR("open f1");
        int fd2 = open(argv[2], O_WRONLY);
        if (fd2 < 0)
            PRINT_ERR("open f2");
        
        char str[10];
        ssize_t res;

        //置位光标到文件的一半处
        lseek(fd1, size / 2, SEEK_SET);
        lseek(fd2, size / 2, SEEK_SET);
        while (1) {

            res = read(fd1, str, sizeof(str));
            if (res <= 0) {
                puts("子进程拷贝结束!");
                break;
            }
            write(fd2, str, res);
        }
        close(fd2);
        close(fd1);
        exit(0);
    } else
        PRINT_ERR("fork");

    return 0;
}
y@DESKTOP-1DH5HNK:~/23071/IO/04day$ ls
01test.c  02test.c  03test.c  a.out  exc.c  test.bmp
y@DESKTOP-1DH5HNK:~/23071/IO/04day$ ./a.out test.bmp cp.bmp
子进程拷贝结束!
父进程拷贝结束!
y@DESKTOP-1DH5HNK:~/23071/IO/04day$ diff test.bmp cp.bmp 
y@DESKTOP-1DH5HNK:~/23071/IO/04day$ 

你可能感兴趣的:(linux,c语言)