fork()ing with c++ and creating 4 childs of a parent

150 views Asked by At

i am fork()ing and creating 4 child processes that runs at the same time(do a busy work), but the parent needs to wait until all child exit. i feel like i can code it in a better way.. any suggestion or does it look okay? (i am required to keep this format of 2 fonctions and main)

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;
}
1

There are 1 answers

0
Armali On

man waitpid:

The call wait(&status) is equivalent to:

       waitpid(-1, &status, 0);

so you can simplify that a bit.