【问题标题】:fork()ing with c++ and creating 4 childs of a parentfork() 使用 c++ 创建父级的 4 个子级
【发布时间】:2015-06-11 03:38:22
【问题描述】:

我正在 fork() 并创建 4 个同时运行的子进程(做一个忙碌的工作),但父进程需要等到所有子进程退出。 我觉得我可以用更好的方式对其进行编码.. 有什么建议或者看起来还可以吗? (我需要保持这种格式的 2 功能和主要)

using namespace std;

void simulateBusyWork(char, pid_t);
pid_t performFork();

int main()
{
    srand(time(NULL));
    performFork();
    return 0;
}

pid_t performFork() {

    pid_t pid;

    //create four child processes
    for (int i = 0; i < 4; ++i) {
        pid = fork();
        if (pid<0) {
            continue;
        } else if (pid == 0) {
            break;
        } 
    }

    //fork failed
    if (pid < 0) {
        fprintf(stderr, "Fork failed./n"); 
        return 1;
    }

    //child process do busy work
    else if (pid == 0) {
        cout << "A child process with PID " << getpid() << " was created." << endl;
        pid = getpid();
        simulateBusyWork('C', pid);
        _exit(0);
    }

    //parent process do busy work
    else if(pid > 0){
        simulateBusyWork('P', getpid());

        //parent process waits for children to exit
        int status, exited;
        //print which child has exited
        for (int i = 0; i < 4; i++) {
            exited = waitpid(-1, &status, 0);
            cout << "P" << getpid() << ": Process " << exited << " has exited." << endl;
        }
    }



    return pid;
}

void simulateBusyWork(char ch, pid_t pid) {

    for (int i=0 ; i < 4; i++) {        
        cout << ch << pid << ": " << i << endl;
        //if (i < 4)
            sleep(1);
    }
    cout << "Process " << ch << pid << " has finished its work." << endl;
}

【问题讨论】:

标签: c++ c shell fork


【解决方案1】:

man waitpid:

调用wait(&amp;status)是等价的 到:

       waitpid(-1, &status, 0);

所以你可以稍微简化一下。

【讨论】:

    猜你喜欢
    • 2015-12-26
    • 1970-01-01
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2015-04-03
    • 2017-12-09
    • 1970-01-01
    • 2014-02-06
    相关资源
    最近更新 更多