线程中fork函数的使用

一、线程中fork函数的是使用(线程与进程的结合)

线程中调用fork函数创建子进程,子进程仅仅执行调用fork函数的这个线程,其他的线程不会被调用。

画图解释:

示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>

//线程中fork函数的使用
//在主线程中fork,再次验证只执行fork函数创建的这个线程
void *fun(void*arg)
{
    while(1)
    {
        sleep(1);
        printf("pthread(%d)\n",getpid());
    }
}

void main()
{
    fork();
    while(1)
    {
        sleep(1);
        printf("main(%d)\n",getpid());
    }
}
//在函数线程中fork
/*
void *fun(void *arg)
{
    if(fork()==0)
    {
        printf("child(%d)\n",getpid());
    }
    else
    {
        printf("pthread(%d)\n",getpid());
    }

}

void main()
{
    pthread_t th;
    int res=pthread_create(&th,NULL,fun,NULL);
    assert(res==0);
    while(1)
    {
        sleep(1);
        printf("main(%d)\n",getpid());
    }
}

在主线程中fork打印结果:
        main(3239)
        main(3240)
        ...
在函数线程中fork打印结果:
        pthread(3286)
        child(3288)
        main(3286)
        main(3286)
        ...
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值