如何处理多线程进程的 fork 错误?
我正在开发一个多线程进程,它分叉来执行另一个进程。有时,如果执行文件不存在,fork 可能会出错。由于此进程在分叉之前有多个线程运行,因此我有几个问题:
- 线程是否复制到分叉进程。
使用多线程进程处理 fork 错误的最佳实践是什么。例如:
/* 在多线程进程中 */ pid = fork(); 如果(pid==0) { execlp(文件名,文件名,NULL); fprintf(stderr, "文件名不存在"); /* 如果有多个线程正在运行我该怎么办 从叉子上? */ 退出(-1); }
I am working on a multithreaded process that forks to execute another process. Sometimes, the fork may error if the execution file does not exist. Since this process has multiple threads running prior to fork I have a couple questions:
- Are threads copied over to the forked process.
What is the best practice to handling an error from fork with a multithreaded process. For example:
/* in a multithreaded process */ pid = fork(); if(pid == 0) { execlp(filename, filename, NULL); fprintf(stderr, "filename doesn't exist"); /* what do i do here if there's multiple threads running from the fork? */ exit(-1); }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,如果可执行文件不存在,
fork
不会出错。在这种情况下,exec
会出错。但是,对于您的实际问题,POSIX指出fork
使用单个线程创建一个新进程,该线程是调用的线程的副本>分叉。有关详细信息,请参阅此处:
所以你所拥有的是好的,如果有点稀疏:-)
单个线程将在子进程中运行,如果你不能
执行
另一个程序,记录一条消息并退出。并且,在基本原理部分,它解释了为什么这样做:
Well, the
fork
doesn't error if the executable file doesn't exist. Theexec
errors in that case. But, to your actual question, POSIX states thatfork
creates a new process with a single thread, a copy of the thread that calledfork
. See here for details:So what you have is okay, if a little sparse :-)
A single thread will be running in the child and, if you cannot
exec
another program, log a message and exit.And, in the rationale section, it explains why it was done that way: