【问题标题】:Does the fork command work with a multi threaded application?fork 命令是否适用于多线程应用程序?
【发布时间】:2014-07-17 14:24:44
【问题描述】:

我尝试 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;
};

它给出以下输出,其中不包含子进程的第二个线程写入的任何信息。

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

第二个线程发生了什么?

【问题讨论】:

    标签: c++ c multithreading fork


    【解决方案1】:

    只有调用线程被分叉。

    来自docs

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

    【讨论】:

      【解决方案2】:

      人叉

      • 子进程是用一个单线程创建的——那个 这称为 fork()。整个病毒—— 父级的实际地址空间在子级中复制,包括互斥锁的状态、连接 diition 变量和其他 pthreads 对象; pthread_atfork(3) 的使用可能有助于 处理这可能导致的问题。

      【讨论】:

        猜你喜欢
        • 2013-01-23
        • 1970-01-01
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-02-09
        • 2016-10-29
        相关资源
        最近更新 更多