CreateThread vs fork()

前端 未结 6 1159
余生分开走
余生分开走 2020-12-20 23:05

Do we have any sort of relationship between fork() and CreateThread? Is there anything that CreateThread internally calls fork()?

相关标签:
6条回答
  • 2020-12-20 23:16

    You might want to know Microsoft provides fork() in high-end versions of Windows with component called Subsystem for UNIX-based Applications (SUA). You can find details in my answer here.

    0 讨论(0)
  • 2020-12-20 23:17

    In NT, the fundamental working unit is called a thread (ie NT schedules threads, not processes.). User threads run in the context of a process. When you call CreateThread, you request the NT kernel to allocate a working unit within the context of your process (you also have fibres that are basically threads you can schedule yourself but that's beyond the topic of your question).

    When you call CreateThread you provide the function with an entry point that is going to be run after the function is called. The code must be within the virtual space of the process and the page must have execution rights. Put simply, you give a function pointer. ;)

    fork() is an UNIX function that requests the kernel to create copy of the running process. The parent process gets the pid of the child process and the child process gets 0 (this way you know who you are).

    If you wish to create a process in Windows, you call the CreateProcess function, but that doesn't behave like fork(). The reason being that most of the time you will create threads, not processes.

    As you can see, there is no relation between CreateThread and fork.

    0 讨论(0)
  • 2020-12-20 23:18

    The Windows and Unix process model is fundamentally very different, so there is no way of directly mapping the API from one on top of the other.

    fork() clones the current process into two. In the parent process, fork() returns the pid, and in the child it returns 0. This is typically used like this:

    int pid;
    if (pid = fork()) {
        // this code is executed in the parent
    } else {
        // this code is executed in the child
    }
    

    Cygwin is an emulation layer for building and running Unix applications on Windows which emulates the behavior of fork() using CreateProcess().

    0 讨论(0)
  • 2020-12-20 23:26

    Found this link which i believe could be helpful in clearing few facts regarding forking/threading. Sharing over here: http://www.geekride.com/index.php/2010/01/fork-forking-vs-threading-thread-linux-kernel/

    0 讨论(0)
  • 2020-12-20 23:38

    fork() only exists on Unix systems and it creates a new process with the same state as the caller. CreateThread() creates a new thread in the same process.

    0 讨论(0)
  • 2020-12-20 23:40

    CreateThread - is for threads, fork - is for creating duplicate process. And there is no native way to have fork functionality for windows (at least through Win32 ).

    0 讨论(0)
提交回复
热议问题