【发布时间】:2023-03-04 00:52:01
【问题描述】:
我希望在相应的子进程使用 exec 系统调用更改其映像之前,在子进程中创建一个线程。然而,看起来 pthread_create 调用被忽略了。
pthread_t thread;
pthread_attr_t attribute;
pthread_attr_init(&attribute);
pthread_attr_setdetachstate(&attribute, PTHREAD_CREATE_DETACHED);
pid_t cid = fork();
if(cid == 0) //CHILD Process
{
switch(x->option)
{
case 1: pthread_create(&thread, &attribute, compressShow, NULL);
execl("/home/aamir/Lab/ass3/compression", "compression", source, destination, NULL);
cout<<"Execution failed."<<endl; break; //This segment will execute if exec fails.
}
else //PARENT Process
{
wait(0); //Prevents termination of original main until forked exec completes execution
pthread_cancel(thread);
}
线程基本上只是一个进度显示,旨在输出'.' (点)与分叉的孩子一致。
如果我删除 exec 调用,线程会执行。我在谷歌上搜索并在某个地方读到你不能在 fork 和 exec 之间使用 pthread_create,这与异步安全函数有关。你能帮忙吗?
【问题讨论】:
-
每个进程都有自己的线程集和自己的地址空间。所以父母不会看到孩子创建的线程。
-
我看到的一种可能的解决方案是在 fork 之前在父级中创建线程。还有其他可能的解决方法吗?
-
是的,在父级中创建线程。同时创建一个
pipe。让子进程在管道上写,父进程中的线程读取它。
标签: c++ linux pthreads exec fork