首页 > 解决方案 > 如何在子进程结束后立即捕获它?

问题描述

我写了一个使用fork的复制函数,以使该函数在后台运行,子进程应该复制文件,而父进程不会等待子进程完成,我的问题是我想当孩子完成复制文件时打印" copying was complete "按摩,但我不知道如何在孩子进程结束后立即捕捉到蚂蚁帮助?

void copyFunction::execute() {

    char *buff = new char[1024]();
    int fdRead = open(args[1], O_RDONLY);
    if (fdRead == -1) {
        perror(" error: open failed");
        return;
    }

    int fdWrite = open(args[2], O_WRONLY | O_TRUNC);
    if (fdWrite ==-1) {                // if we couldn't open the file then create a new one (not sure if we supposed to this ?)
        fdWrite = open(args[2], O_WRONLY | O_CREAT, 0666);
        if (fdWrite == -1) {
            perror(" error: open failed");
            return;
        }
    }

    PID = fork();
    if (PID == 0) {
        setpgrp();

        int count = read(fdRead, buff, 1);  /// read from the file fd1 into fd2
        while (count != -1) {
            if (!count) {
                break;
            }
            if (write(fdWrite, buff, 1) == -1) {
                perror(" error: write failed");
                return;  // not sure if we should return
            }
            count = read(fdRead, buff, 1);
            if (count == -1) {
                perror(" error: read failed");
                exit(1) ;
            }
        }
        exit(1) ;
    }  if (PID > 0) { 
            SmallShell::getInstance().Jobs_List.addJob(SmallShell::getInstance().currentCommand, false);
            return;

    } else {
        perror(" error: fork failed");
    }
}

在哪里打电话?

 cout << "copying was complete" << endl;

标签: c++forkparent-child

解决方案


使用 wait() 调用。

PID = fork();
if(PID > 0){
    wait(NULL);
    cout << " copying is complete" << endl;

}

推荐阅读