你在找什麼是進程間條件變量。 https://en.wikipedia.org/wiki/Monitor_(synchronization)
它會工作(大約)方式: -
分叉你之前設置一個變量,詢問孩子等着: - child_continue = false
1)子進程開始執行(或父,沒有按「T物質)
- 如果變量
child_continue == false
- 休眠條件變量和等待信號從父
2.)父進程等待其運行的機會(注意運行順序無關緊要)。當父進程準備好運行時,它可以通過子PID(或其他)執行任何想要的操作,並指示子進程繼續。
爲了做到這一點,你需要進程間互斥和進程間條件變量。
//#include "pthread.h" in main file
//create IPC MUTEX which can be shared by both child and parent.
pthread_mutexattr_t mutex_attr;
pthread_condattr_t cond_attr;
pthread_mutex_t mtx;
pthread_cond_t cond;
if (0!= pthread_mutexattr_init(&mutex_attr))
{
//errror handling
}
if (0!= pthread_condattr_init(&cond_attr))
{
//errror handling
}
if (0 != pthread_condattr_setpshared(&cond_attr,PTHREAD_PROCESS_SHARED)
{
//error handling
}
if (0 != pthread_mutexattr_setpshared(&mutex_attr,PTHREAD_PROCESS_SHARED)
{
//error handling
}
if (0 !=pthread_mutex_init(&mtx,&mtx_attr))
{
//error handling
}
if (0 !=pthread_cond_init(&cond,&cond_attr))
{
//error handling
}
boolean child_continue = false;
//now fork !!
pid_t pi = fork();
if (pi ==0) //child
{
if (0 !=pthread_mutex_lock(&mtx))
{
//error handling
}
while (!child_continue) //wait until we receive signal from parent.
{
if (0 !=pthread_cond_wait(&cond,&mtx))
{
//error handling
}
}
if (0 !=pthread_mutex_unlock(&mtx))
{
//error handling
}
//Parent is done!! either we woke up by condition variable or, parent was done before hand
//in which case, child_continue was true already.
}
else
{
//in parent process do whatever you want with child pid (pi variable)
//once you are done, set child_continue to true and wake up child.
if (0 !=pthread_mutex_lock(&mtx))
{
//error handling
}
child_continue = true;
if (0 !=pthread_cond_signal(&cond))
{
//error handling
}
if (0 !=pthread_mutex_unlock(&mtx))
{
//error handling
}
}
如何使用管道並讓子進程等待管道中出現的東西? – 2013-04-29 01:26:40
使用信號量。 – Duck 2013-04-29 01:26:51
你打算如何處理父母的孩子的PID?您可以在執行子應用程序之前簡單地讓分叉的孩子等待父母準備好嗎?爲什麼不? – 2013-04-29 04:28:03