你在找什么是进程间条件变量。 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