How to use fork() in unix? Why not something of the form fork(pointerToFunctionToRun)?

前端 未结 8 2125
盖世英雄少女心
盖世英雄少女心 2021-02-06 05:01

I am having some trouble understanding how to use Unix\'s fork(). I am used to, when in need of parallelization, spawining threads in my application. It\'s always s

8条回答
  •  野性不改
    2021-02-06 05:28

    It would be more valid to ask why CreateNewThread doesn't just return a thread id like fork() does... after all fork() set a precedent. Your opinion's just coloured by you having seen one before the other. Take a step back and consider that fork() duplicates the process and continues execution... what better place than at the next instruction? Why complicate things by adding a function call into the bargain (and then one what only takes void*)?

    Your comment to Mike says "I can't understand is in which contexts you'd want to use it.". Basically, you use it when you want to:

    • run another process using the exec family of functions
    • do some parallel processing independently (in terms of memory usage, signal handling, resources, security, robustness), for example:
      • each process may have intrusive limits of the number of file descriptors they can manage, or on a 32-bit system - the amount of memory: a second process can share the work while getting its own resources
      • web browsers tend to fork distinct processes because they can do some initialisation then call operating system functions to permanently reduce their privileges (e.g. change to a less-trusted user id, change the "root" directory under which they can access files, or make some memory pages read-only); most OSes don't allow the same extent of fine-grained permission-setting on a per-thread basis; another benefit is if a child process seg-faults or similar the parent process can handle that and continue, whereas similar faults in multi-threaded code raise questions about whether memory has been corrupted - or locks have been held - by the crashing thread such that remaining threads are compromised

    BTW / using UNIX/Linux doesn't mean you have to give up threads for fork()ing processes... you can use pthread_create() and related functions if you're more comfortable with the threading paradigm.

提交回复
热议问题