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

前端之家收集整理的这篇文章主要介绍了c – 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

第二个帖子怎么了?

解决方法

只分叉调用线程.

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.

原文链接:https://www.f2er.com/c/239504.html

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