c – fork命令是否适用于多线程应用程序?

前端之家收集整理的这篇文章主要介绍了c – fork命令是否适用于多线程应用程序?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图分叉多线程应用程序.似乎fork没有复制我的第二个帖子.

这是我的代码

  1. #include <stdlib.h>
  2. #include <pthread.h>
  3. #include <iostream>
  4. #include <linux/unistd.h>
  5. #include <iostream>
  6. #include <sys/types.h>
  7. #include <sys/wait.h>
  8. #include <signal.h>
  9. #include <st@R_301_410@.h>
  10. #include <unistd.h>
  11. #include <string>
  12. #include <unistd.h>
  13. #include <stdlib.h>
  14. #include <sys/ioctl.h>
  15.  
  16. using namespace std;
  17.  
  18. void Loop(const char* zThread)
  19. {
  20. while (true)
  21. {
  22. sleep(2);
  23. cout << "LOOP : " << zThread << " : " << getpid() << endl;
  24. }
  25. }
  26.  
  27. void *MyFunction(void *pData)
  28. {
  29. Loop("Second");
  30. };
  31.  
  32. int main()
  33. {
  34. pthread_t thread1;
  35.  
  36. pthread_create(&thread1,NULL,MyFunction,NULL);
  37.  
  38. int iPID = fork();
  39.  
  40. if (iPID == 0)
  41. cout << "Child : " << getpid() << endl;
  42. else
  43. cout << "Parent : " << getpid() << endl;
  44.  
  45. Loop("First");
  46.  
  47. return EXIT_SUCCESS;
  48. };

它提供以下输出,该输出不包含子进程的第二个线程写入的任何信息.

  1. test_1/ss> ./a.out
  2. Parent : 11877
  3. Child : 11879
  4. LOOP : Second : 11877
  5. LOOP : First : 11877
  6. LOOP : First : 11879
  7. LOOP : Second : 11877
  8. LOOP : First : 11877
  9. LOOP : First : 11879
  10. LOOP : Second : 11877
  11. LOOP : First : 11877
  12. LOOP : First : 11879
  13. LOOP : Second : 11877
  14. LOOP : First : 11877
  15. LOOP : First : 11879
  16. LOOP : Second : 11877
  17. LOOP : First : 11877
  18. LOOP : First : 11879
  19. LOOP : Second : 11877
  20. LOOP : First : 11877
  21. LOOP : First : 11879

第二个帖子怎么了?

解决方法

只分叉调用线程.

docs

A process shall be created with a single thread. If a multi-threaded process calls fork(),the new process shall contain a replica of the calling thread and its entire address space,possibly including the states of mutexes and other resources. Consequently,to avoid errors,the child process may only execute async-signal-safe operations until such time as one of the exec functions is called.

猜你在找的C&C++相关文章