Can I call chdir or setenv after fork on Mac OS X?

On OS X, the fork man page says this:

There are restrictions on what you can do in the child process. To be completely safe, you should limit yourself to performing safe operations on the asynchronous signal until one of the exec functions is called. All APIs, including global data characters, in any structure or library should be considered unsafe after fork (), unless explicitly documented, to be safe or safe for an asynchronous signal. If you need to use these frameworks in a child process, you must run the command. In this situation, it is wise to fulfill yourself.

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

Berkeley 4th distribution June 4, 1993 Berkeley 4th distribution

I would have thought that chdir (2) would call safely between fork () and exec (), but its man page did not say that it is safe for asynchronous calls. Is this essentially unsafe? If so, did I really expect to change the directory before fork ()? It seems unreasonable to me.

The same goes for setenv (3). Given that it calls malloc (), I assume that it is probably unsafe. But there is no equivalent of execvp that allows me to pass in an environment. In particular, execvp is looking for PATH. The closest equivalent I could find accepts an arg environment, execve () does not look for PATH.

+1
source share
1 answer

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

To my knowledge, all standard C library functions, including chdir() , ARE are safe to use after fork() .

+1
source

Source: https://habr.com/ru/post/1211045/


All Articles