Linux/Windows上的线程/进程比较

Ren*_*h G 5 c linux windows multithreading process

我有一些在Windows中使用线程和进程的经验.

有人可能会解释一下,Linux中的线程和进程是否可能映射到Linux中?

那意味着,Windows中的线程= Linux中的线程? - >有道理吗?Windows中的进程= Linus中的进程? - >有道理吗?

如果相同,我在Windows中有CreateThread()和CreateProcess()调用,linux中的等效调用是什么?

我已经阅读了一些SO中的帖子,但大多数都没有清除我的疑虑.所以想开始一个新帖子.

如果我用一些简单的例子(C编程)得到一些解释,那就太好了.

Tud*_*dor 6

好吧,在Linux中有相同的调用目的,但它们的工作方式略有不同,至少对于进程机制而言.

  1. 对于线程,您可以使用pthread_create.它的工作方式非常类似CreateThread,除了一些参数不同.应该很容易使用.这是一个很好的教程:https://computing.llnl.gov/tutorials/pthreads/

  2. CreateProcess为了启动外部过程而进行模拟并不是那么简单.你需要着名的fork/exec组合.首先,您需要fork在主进程内部调用以生成子进程.通过复制初始过程来创建此子项.然后,您可以通过检查返回的值来控制流量fork:

 int rv = fork(); 
 // new process was spawned here. The following code is executed 
 // by both processes.
 if(rv == 0)
 {
     // we are in the child process
 }
 else
 {
     // we are in the parent
 }
Run Code Online (Sandbox Code Playgroud)

rv孩子的基本上是0,父母的孩子的pid 基本上是0.我希望到目前为止我没有失去你.:)

继续,您需要调用其中一个exec函数来启动外部进程:

 int rv = fork(); 
 // new process was spawned here. The following code is executed 
 // by both processes.
 if(rv == 0)
 {
     execl("/bin/ls", "ls", NULL); // start the ls process
 }
 else
 {
     // we are in the parent
 }
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,我正在启动/bin/ls外部进程,它打印当前文件夹的内容.

这是一个简单的完整示例:http://flinflon.brandonu.ca/dueck/2001/62306/Processes/Unix%20Examples.htm

现在你可能想知道为什么你需要首先打电话fork,为什么execl还不够.这是因为在execl终止程序调用程序之后,当前进程也会终止,并且您不希望在主进程中发生这种情况.