Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it prohibited to use fork without exec in mac?

Tags:

c++

c

fork

macos

exec

My question is quite simple. On Linux it is quite popular to use fork without exec

However, I have found that on MacOS this is not possible (see fork manual)

https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man2/fork.2.html

There are limits to what you can do in the child process. To be totally safe you should restrict your-self yourself self 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.

This seems strange to me? What is the reason? Is it possible to workaround it?

like image 401
Georgy Buranov Avatar asked Sep 17 '13 16:09

Georgy Buranov


People also ask

What happens if you fork without exec?

exec without forkThe current process image is replaced with something different. Restarting the currently running program (might for example happen when you SIGHUP or such a server process, reloading everything and doing a completely fresh start).

Does fork work on Mac?

Fork - a fast and friendly git client for Mac and Windows.

What is the difference between fork and exec?

fork vs execfork starts a new process which is a copy of the one that calls it, while exec replaces the current process image with another (different) one. Both parent and child processes are executed simultaneously in case of fork() while Control never returns to the original program unless there is an exec() error.


1 Answers

It's okay to use fork in OS X, under the same restrictions you would use fork with Linux. Linux has similar caveats or via the Wayback Machine.

If you are building an application that is single-threaded and relies on core UNIX APIs and design philosophy, you should be fine. If you are linking to additional libraries, you should be intimately familiar with their behavior. Imagine linking to a library that started a background thread – after forking you'd be in a potentially undefined state, given only the thread that called fork is cloned.

OS X offers some awesome features for taking advantage of multiple cores, such as Grand Central Dispatch that may be worth considering.

I'd recommend you read this article by Mike Ash on fork safety under OS X.

like image 96
Stuart Carnie Avatar answered Sep 18 '22 13:09

Stuart Carnie