0

i have some trouble with fork and its copy on write system. I will create params.writersCount procesess and in each i need to get its internal id( from 1 to params.writersCount). So in child i am waiting for parent process, that initialize childs internal id (writers[i] = processId). Then i can call writerSimulation and pass context address like argument, because in context.id is now right internal id for that child, because of copy on write system (context.id = j+1 will force unix to copy page, so each child has then own context copy with its internal id). But if i try to use context.id in writerSimulation function, i am getting 0. What i am doing wrong?

for(int i = 0; i < params.writersCount; i++)
{
    pid_t processId = fork();

    if(!processId)
    {   
        srand((unsigned int)(seconds+getpid()));
        while(!context.id)
        {
            for(int j = 0; j < params.writersCount; j++)
            {   
                if(writers[j] == getpid())
                {   
                    context.id = j+1;
                }
            }
            struct timespec wait = {.tv_sec = 0, .tv_nsec = 500000};
            nanosleep(&wait, NULL);
        }
        int simError = writerSimulation(&context);
        return simError;
    }

    writers[i] = processId;
}
4

2 に答える 2

0

It's not entirely clear to me, but it looks like you are trying to have the parent modify the writers array in the child. That will not work. After the fork, any writes that the parent makes will not be seen in the child, since copy on write applies to both the child and the parent. Also, using nanosleep to wait is not even remotely reliable. An easy way to communicate to the child is to open a pipe before the fork and use that for synchronization and passing data. simply have the parent write data into the pipe. The child blocks on a read rather than nano-sleeping, so synchronization is provided by read.

于 2012-04-28T16:12:58.780 に答える
0

You cannot in the child access a value assigned by the parent after the fork. There are several options:

  • Change your overall approach so this is not needed - rely on information available before the fork or derived independently in both parent and child after it.

  • Use a means of interprocess communication -sockets, pipes, shared memory, etc

于 2012-04-28T16:17:21.053 に答える