wanovak
wanovak

Reputation: 6127

Fork child and parent running separate code

I'm trying to dot product two vectors, with each process taking on a separate starting and ending index. What seems to be happening is that the code gets executed twice.

void DotProduct::MultiProcessDot()
    {
    pid_t pID,w;
    int status;   
    unsigned int index = mNumberOfValuesPerVector / 2;

    if((pID = fork()) < 0){
        cout << "fork error" << endl;
    }
    else if(pID == 0){ /* child */
        ProcessDotOperation(0, index);
        exit(EXIT_FAILURE);
    }
    else{ /* parent */
        ProcessDotOperation(index, mNumberOfValuesPerVector);
        w = waitpid(pID, &status, WNOHANG);
        if(w == 0){
            cout << "alive" << endl;
        }else if(w == -1){
            cout << "dead" << endl;
        }
    }
}

ProcessDotOperation calculates the dot product using shared memory with sem_wait() and sem_post(). What seems to be happening is this:

Note: I may have a fundamental misunderstanding of what's happening, so by parent and child, I'm referring to the comments in the code as to which process I think is running.

How do I make it such that the child runs ProcessDotOperation once, the parent runs ProcessDotOperation once, and then the program continues operation?

Any help is appreciated.

Edit

If I print before the fork(), and change w = waitpid(pID, &status, WNOHANG); to w = waitpid(pID, &status, 0);, here's the output:

forking

parent

child

forking

parent

child

continued execution...

Here's the code of ProcessDotOperation:

void DotProduct::ProcessDotOperation(unsigned int startIndex, unsigned int endIndex)
{

    for(unsigned int i = startIndex; i < endIndex; i++){
        sem_wait(mSem);

        mShmProductId += mVectors[0][i] * mVectors[1][i];
        cout << startIndex << " " << endIndex << " " << i << endl;

        sem_post(mSem);
    }
}

Upvotes: 0

Views: 368

Answers (2)

Robᵩ
Robᵩ

Reputation: 168616

Someone is calling MultiProcessDot a second time.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 753495

I think you need a loop around the waitpid(). As it is written, you wait once, without hanging around for a dead child, returning immediately if the child is not yet dead. This allows the parent to go on with other activities, of course.

I'm not sure it's a complete explanation of what you observe, but we can't see your trace code. Print things like the process's PID with each message.

Upvotes: 1

Related Questions