简体   繁体   中英

is there any simplest way to wait in a child process until a flag / event change?

this is my sample program but it work as flag does not affect in child process and even sem_wait , sem_trywait also wont work, apart from signals and fcntl is there any other way to wait till particular event triggered.

#include "header.h"
void main()
{
    int flag = 1;
    pid_t cpid;
    sem_t semobj;
    int value;
    cpid = fork() ;
    sem_init ( &semobj, 0, 2);
    if ( cpid == 0)
    {
        printf ("Chile Process id = %d, PPID= %d\n",getpid(),getppid());
        while ( FLAG ); // here i need to wait until parent process disables the flag
        //sem_trywait ( &semobj);
        //sem_getvalue ( &semobj, &value );
        printf ( "After Wait =%d\n", FLAG );
        sleep(10);
    }
    else
    {
        printf( "Parent Process id =%d\n",getpid() );
        sleep(3);
        printf( "Setting Flag value\n" );
        FLAG = 0; // here i need to set a flag
        sleep(7);

    }
}

I guess there's no the "simplest way".

The thing is that you're dealing with two separate processes here. And if you want to communicate anything between the two you have to use some kind of IPC (Inter Process Communications) mechanism. I'd suggest for you to read something like this on the subject and pick one.

You code doesn't work as you'd like it to because once you've fork() ed you have two address spaces each with its own set of variables (including semaphore variables). So any action parent performs on those variables in its address space does not affect any of the variables in child's address space, thus no communication happens.

I recommend reading whats written in the section "Named Semaphores" on this page .

Your problem is that you don't name your semaphores and therefore your semaphore gets copied for the child process. That means, as Igor already explained in his answer, that the semaphore variable is not the same for child and parent process.

A named semaphore can be shared between two processes so your parent process would be able to signal your child process.

Take a look at http://www.yendor.com/programming/unix/apue/ch8.html , the Synchronization Library section.

Basically you want the

TELL_WAIT
TELL_PARENT
TELL_CHILD
WAIT_PARENT
WAIT_CHILD

functions.

The linked examples use signals to implement them, but you should also be able to implement them with pipes , shared memory + posix semaphores , or SysV semaphores .

If you want to use Posix semaphores, the semaphore needs to be in shared memory (shm_open) and initialized to 0 before forking.


Also, that is not how you use fork—take a look at my answer here (and subtract the exec part): How to start process on Linux OS in C, C++

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM