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

Suj*_*ane 6 c c++ multithreading fork

我试图分叉多线程应用程序.似乎fork没有复制我的第二个帖子.

这是我的代码:

#include <stdlib.h>
#include <pthread.h>
#include <iostream>
#include <linux/unistd.h>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <string>
#include <unistd.h>
#include <stdlib.h>
#include <sys/ioctl.h>

using namespace std;

void Loop(const char* zThread)
{
    while (true)
    {
        sleep(2);
        cout << "LOOP : " << zThread << " : " << getpid() << endl;
    }
}

void *MyFunction(void *pData)
{
    Loop("Second");
};

int main()
{
    pthread_t thread1;

    pthread_create(&thread1, NULL, MyFunction, NULL);

    int iPID = fork();

    if (iPID == 0)
        cout << "Child : " << getpid() << endl;
    else
        cout << "Parent : " << getpid() << endl;

    Loop("First");

    return EXIT_SUCCESS;
};
Run Code Online (Sandbox Code Playgroud)

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

test_1/ss> ./a.out
Parent : 11877
Child : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
LOOP : Second : 11877
LOOP : First : 11877
LOOP : First : 11879
Run Code Online (Sandbox Code Playgroud)

第二个帖子怎么了?

nos*_*nos 5

只分叉调用线程.

来自文档:

应使用单个线程创建进程.如果多线程进程调用fork(),则新进程应包含调用线程的副本及其整个地址空间,可能包括互斥锁和其他资源的状态.因此,为了避免错误,子进程可能只执行异步信号安全操作,直到调用其中一个exec函数为止.