我可以在 Mac OS X 上 fork 后调用 chdir 或 setenv 吗?

发布于 2024-12-23 05:30:37 字数 592 浏览 6 评论 0原文

在 OS X 上,fork 的手册页是这样说的:

您在子进程中可以执行的操作是有限的。为了完全安全,您应该限制自己只执行异步信号安全操作,直到调用 exec 函数之一为止。任何框架或库中的所有 API(包括全局数据符号)在 fork() 之后都应被假定为不安全,除非明确记录为安全或异步信号安全。如果需要在子进程中使用这些框架,则必须exec。在这种情况下,执行自己的命令是合理的。

根据手册页的页脚,这可能已经存在很长时间了:

第四届伯克利分布 1993 年 6 月 4 日 第四届伯克利分布

我本以为 chdir(2) 在 fork() 和 exec() 之间调用是安全的,但它的手册页并没有说它对于异步调用是安全的。事实上,它不安全吗?如果是这样,我真的希望在 fork() 之前更改目录吗?对我来说似乎不合理。

setenv(3) 也是如此。考虑到它调用了 malloc(),我猜它可能不安全。但是没有 execvp 的等效项可以让我传递环境。具体来说,execvp 搜索 PATH。我能找到的最接近的等效函数,采用环境参数 execve(),不会搜索 PATH。

On OS X, the man page for fork says this:

There are limits to what you can do in the child process. To be totally safe you should restrict yourself to only executing async-signal safe operations until such time as one of the exec functions is called. All APIs, including global data symbols, in any framework or library should be assumed to be unsafe after a fork() unless explicitly documented to be safe or async-signal safe. If you need to use these frameworks in the child process, you must exec. In this situation it is reasonable to exec yourself.

Based on the footer of the man page, this has probably been there a long time:

4th Berkeley Distribution June 4, 1993 4th Berkeley Distribution

I'd have thought that chdir(2) would be safe to call between fork() and exec(), but its man page does not say that it's safe for async calls. Is it, in fact, unsafe? If so, am I really expected to change directory before fork()? Seems unreasonable to me.

Same goes for setenv(3). Considering that it calls malloc(), I guess that it's probably not safe. But there is no equivalent of execvp that allows me to pass an environment. Specifically, execvp searches the PATH. The closest equivalent I could find that takes an environment arg, execve(), does not search the PATH.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

记忆で 2024-12-30 05:30:37

您引用的第一段文本(“有限制......”)是专门为 Mac OS X 添加的 - 它试图指出大多数 Apple 的库和框架(AppKit、Carbon、Foundation 等)将fork() 之后无法正常工作。

据我所知,所有标准 C 库函数,包括 chdir(),都可以在 fork() 之后安全使用。

The first block of text you're quoting ("There are limits...") was added specifically for Mac OS X -- it's trying to point out that most of Apple's libraries and frameworks (AppKit, Carbon, Foundation, etc) will not work properly after a fork().

As far as I'm aware, all standard C library functions, including chdir(), ARE safe to use after fork().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文