我有一个程序在循环中创建多个fork()之后,在父进程之后执行所有子进程。
但是,在终止每个子进程之前先运行父进程。

im childprocess : 18389
parent process done
im childprocess : 18390
parent process done
im childprocess : 18391
parent process done


这是我如何使用fork()调用的代码

for (int file = 0; file < files_count; file++) {
        pid_t pid = fork();
        int file_loc = file + 2;

        if (pid == 0) {
            // child process
            occurrences_in_file(argv[file_loc], argv[1]);
            break;
        } else if (pid > 0) {
            // parent process
            parentProcess();
        } else {
            // fork failed
            printf("fork() failed!\n");
            return 1;
        }

    }




void occurrences_in_file(const std::string& filename_,
        const std::string& pattern_);
void occurrences_in_file(const std::string& filename_,
        const std::string& pattern_) {
    int my_pid;





    cout << "im childprocess : " <<  my_pid <<endl;

}




void parentProcess();
void parentProcess() {

    while (true) {
        int status;
        pid_t done = wait(&status);
        if (done == -1) {
            if (errno == ECHILD){

                cout << "parent process done"<< endl;
                break; // no more child processes
            }
        } else {
            if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
                std::cerr << "pid " << done << " failed" << endl;
                _exit(1);
            }
        }

    }


}

最佳答案

在这里,您要在循环的每个迭代中创建一个子进程,然后在同一迭代中等待它。因此,在一次迭代结束时,将创建一个子进程,先打印然后退出,父进程从等待中唤醒,然后打印,从而得到前两行。

类似的输出将用于下一次迭代,因此循环的每次迭代都会得到两行,看起来父级在子级之前执行,但不是。

如果要在所有子进程完成后调用父进程,请执行以下操作。

引入一个全局变量isParent,如果当前进程是父进程,则为true。初始化为零

int isParent = 0;


然后在循环中,将parentProcess()设置为isParent而不是调用1

for (int file = 0; file < files_count; file++) {
    pid_t pid = fork();
    int file_loc = file + 2;

    if (pid == 0) {
        // child process
        occurrences_in_file(argv[file_loc], argv[1]);
        break;
    } else if (pid > 0) {
        // parent process
        isParent = 1;
    } else {
        // fork failed
        printf("fork() failed!\n");
        return 1;
    }

}


然后在for循环之后调用parentProcess如果设置了isParent

if(isParent){
    ParentProcess(files_count)
}


然后在parentProcess(int numChildren)调用中等待所有子进程。

void parentProcess(int numChildren);
void parentProcess(int numChildren) {

while (true) {
    int status;
    int i;
    for(i = 0;i < numChildren; i++){
        pid_t done = wait(&status);
        if (done == -1) {
            if (errno == ECHILD){

                cout << "parent process done"<< endl;
                break; // no more child processes
            }
        } else {
            if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
                std::cerr << "pid " << done << " failed" << endl;
                _exit(1);
            }
        }
    }
}

关于c++ - 所有子进程终止后,将无法运行父进程。,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32947850/

10-15 00:23
查看更多