Is it safe to fork from within a thread?

后端 未结 8 903
-上瘾入骨i
-上瘾入骨i 2020-11-28 04:04

Let me explain: I have already been developing an application on Linux which forks and execs an external binary and waits for it to finish. Results are communicated by shm f

8条回答
  •  难免孤独
    2020-11-28 05:01

    While you can use Linux's NPTL pthreads(7) support for your program, threads are an awkward fit on Unix systems, as you've discovered with your fork(2) question.

    Since fork(2) is a very cheap operation on modern systems, you might do better to just fork(2) your process when you have more handling to perform. It depends upon how much data you intend to move back and forth, the share-nothing philosophy of forked processes is good for reducing shared-data bugs but does mean you either need to create pipes to move data between processes or use shared memory (shmget(2) or shm_open(3)).

    But if you choose to use threading, you can fork(2) a new process, with the following hints from the fork(2) manpage:

       *  The child process is created with a single thread — the
          one that called fork().  The entire virtual address space
          of the parent is replicated in the child, including the
          states of mutexes, condition variables, and other pthreads
          objects; the use of pthread_atfork(3) may be helpful for
          dealing with problems that this can cause.
    

提交回复
热议问题