如何加入一个有fork的线程?

以下是这种情况。

{
    ...
    pthread_create(thread_id, NULL, thread_fun, NULL);
    pthread_join(thread_id, NULL);
    ...
}
void * thread_fun(void * arg)
{
    if(fork())
    {
        printf("In Parent\n");
        pthread_exit(NULL);
    }
    else
    {
         printf("In Child\n");
         pthread_exit(NULL);
    }
}

如何以这样的方式使用pthread_join():我可以在线程中等待子进程和父进程?

评论
第夏山
第夏山

Put all threads into endless loops and then inspect the whole program state with ps, top, htop or similar tools. You will find that the child process only has a single thread, while the parent process has (at least) two.

Now, concerning your question how to use pthread_join() to wait for the child process, you simply can't, because you can only use it to wait for threads in the same process. You could wait for the child process to terminate (waitpid()).

如果以上方法不能解决您的问题(由于您想“等待子进程和父进程”(我想知道哪个进程的上下文),因此有点不清楚),请退后一步并在更高层次上进行描述您正在尝试实现的目标。换句话说,这可能是所谓的“ XY问题”。对该术语进行一些研究,无论如何要学习和理解是一件好事。

点赞
评论