【问题标题】:Is it good to start a child process from a thread of main process从主进程的线程启动子进程好不好
【发布时间】:2017-11-02 01:45:10
【问题描述】:

我的情况如下:

main()
{
 create a thread executing function thread_func();

 another_func();

}

another_func()
{
  //check something and do something.
  // To do something, create a child process.
  // after creating child process, current thread goes in checking state again
  // child process independently running.
}

thread_func()
{
 infinite loop(); // checking something and doing something
}

线程是使用 pthread 创建的。 请告诉:在线程中启动像上面这样的子进程是否很好?如果这样做了会发生什么。

子进程是否创建自己的另一个执行thread_func()的复制线程?

谢谢

【问题讨论】:

标签: c multithreading pthreads fork child-process


【解决方案1】:

这取决于你想做什么...... 在这里,您的线程将永远不会进入another_func(),因为它因为infinite_loop() 而被困在thread_func()。因此,您的主程序将创建子进程。

【讨论】:

    【解决方案2】:

    你的问题不是很清楚你想做什么。 pthread_create() API 采用指向 void* ()(void) 类型函数的指针。实际的线程执行在那个线程上,所以如果你想在一个线程上创建一个子进程,你必须在thread_func()里面做

    如果您使用 fork() API(这是 linux 上的标准方式)创建另一个进程,则会创建一个单独的进程,其中包含父进程的整个内存空间的副本。但是内存将是虚拟的并标记为写入时复制,因此实际上除非您尝试写入内存,否则不会复制内存。

    如果您在调用 fork() 之后还调用了 exec() 或 exec() 系列中的任何其他 API,那么您无需担心复制的内存。在 exec() API 之后,子进程将拥有独立于父进程的自己的内存空间。

    【讨论】:

      猜你喜欢
      • 2015-02-03
      • 2015-11-19
      • 2012-01-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      相关资源
      最近更新 更多