Lavair
Lavair

Reputation: 936

How do I wait inside a child process until the parent process reached a certain point?

PSEUDO-CODE:

Child:
...
wait until parent prints "blabla"
...

Parent:
...
print "blabla"
...

I can't use wait, because that would be the other way around and furthermore, I want to continue the parent process after the print "blabla" parallel to the child process.
I could imagine to share with mmap a pthread_mutex_t variable and solve the issue with mutual exclusion, but I am not sure about that and wanted to ask if there might exists a very easy solution.

Upvotes: 1

Views: 274

Answers (2)

vinoth h
vinoth h

Reputation: 531

Have two global variables,one for mutex lock and another for a signal variable like this.

pthread_cond_t signal = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t cond_mutex = PTHREAD_COND_INITIALIZER;

In your parent thread when you print blabla signal the child thread :

pthread_mutex_lock(&cond_mutex);
pthread_cond_signal(&signal);
pthread_mutex_unlock(&cond_mutex);

In your child thread wait for the signal :

struct timespec time_to_wait = {0, 0};
time_to_wait.tv_sec = time(NULL) + 10;//10 secs
pthread_mutex_lock(&cond_mutex);
status = pthread_cond_timedwait(&signal,&cond_mutex, &time_to_wait);
pthread_mutex_unlock(&cond_mutex);

You can extend this code to handle repeatedly wait for the condition to occur for every 't' seconds within a loop, or simply wait once for 't' seconds and quit. Refer this doc for the return values.

Upvotes: 0

Ganesh_Shinde
Ganesh_Shinde

Reputation: 38

You can use Signals for this, After completing a certain task parent process should send a signal to child process by using Kill system call and by updating the signal handler of the signal child process can do further task.

Child: signal_handler() { ... } main() { signal(SIGINT, signal_handler); while(1);//wait until parent prints "blabla" }

Parent:
...
print "blabla"
 kill(pid_of_child,signal)
 ...

Upvotes: 2

Related Questions