【Linux学习笔记】exec进程替换后,线程是否会被替换

35 篇文章 1 订阅
代码示例展示了一个C++程序,创建两个线程并使用pthread库。主线程在10秒后使用execl函数替换自身为mymain进程。在替换后,原有的线程被终止,只剩下替换后的进程运行。实验观察到,子线程在程序替换后停止,只剩下主线程的tid在新进程中继续运行。
摘要由CSDN通过智能技术生成

实验

// exec_thread_test.cpp
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include<sys/syscall.h>
using namespace std;


//由于pthread用户库内没有gettid()所以需要这个头文件以及下面的函数定义
pid_t gettid()
{
     return syscall(SYS_gettid);
}

void* thread1(void *args) {
    pthread_detach(pthread_self());
    int n = 10;
    while (1) {
        cout << "i am pthread_id: " << pthread_self() << "   thread_id: " << gettid() << endl;
        sleep(2);
    }
    return nullptr;
}

void* thread2(void *args) {
    pthread_detach(pthread_self());
    while (1) {
        cout << "i am pthread_id: " << pthread_self() << "   thread_id: " << gettid() << endl;
        sleep(2);
    }
    return nullptr;
}

int main() {
    pthread_t tid;
    pthread_create(&tid, nullptr, thread1, nullptr);
    sleep(1);
    pthread_create(&tid, nullptr, thread2, nullptr);
    int n = 10;
    while (n--) {
        sleep(1);
    }
    execl("/home/xupeng/learn/test/mymain", "mymain", NULL);
    return 0;
}
// mymain.cpp
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include<sys/syscall.h>
using namespace std;

//由于pthread用户库内没有gettid()所以需要这个头文件以及下面的函数定义
pid_t gettid()
{
     return syscall(SYS_gettid);
}

int main() {
    while (1) {
        cout << "i am execed pthread_id: " << pthread_self() << "   thread_id: " << gettid() << endl;
        sleep(2);
    }
    return 0;
}

在这里插入图片描述
解释一下代码:

  1. 主线程创建两个子进程,相隔1秒
  2. 10s后,主线程进行程序替换,替换的进程为mymain

从实验可以看出,主线程的tid为12287,两个子线程的tid为12288、12306。在被程序替换后,监听exec_thread_test的shell没有了输出,监听mymain的shell开始输出,且(ps -axj | grep main_pid效果 一样)只有主线程一个执行流,之前进程创建的子线程都被关闭了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值