加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 04:58:38 所属栏目:百科 来源:网络整理
导读:我试图分叉多线程应用程序.似乎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#in
我试图分叉多线程应用程序.似乎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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读