0
点赞
收藏
分享

微信扫一扫

Linux编程:fork一个多线程的程序

和谐幸福的人生 2022-04-23 阅读 48
linux

如果一个程序本身是多线程的程序,那么在其中的一个线程里进行fork操作,他的子进程是个单线程的进程还是个多线程的进程呢?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/syscall.h>
#include <pthread.h>
#include <thread>
#include <unistd.h>

using namespace std;

pid_t gettid() 
{
    return syscall(SYS_gettid);
} 

void t_func(void *arg)
{//父进程创建的线程
    printf("pid:%u create thread:%d, id:%u\n", getpid(), *(int*)arg, gettid());
    sleep(15);
    printf("pid:%u exit thread:%d, id:%u\n", getpid(), *(int*)arg, gettid());
}

int main()
{	
	int i = 1;
    printf("parent pid:%u\n", getpid());
    thread t1(t_func, &i);
    sleep(1);
    
	pid_t pid = fork();
	if(pid < 0)
	{//fork failed
		printf("fork failed");		
	}
	else if(pid == 0)
	{//子进程
		printf("child:%u enter\n", getpid());
		sleep(10);
		printf("child:%u exit\n", getpid());
		exit(0);
	}
	else
	{//父进程
		printf("parent:%u waiting child:%u exit\n", getpid(), pid);
		waitpid(pid, 0, 0);
		printf("parent:%u find child:%u exit\n", getpid(), pid);
		printf("parent:%u waiting thread exit\n", getpid());
		t1.join();
		printf("parent:%u find thread exit\n", getpid());		
	}
	return 0;
}

运行程序输出:
parent pid:232479                        //父进程232479开始运行
pid:232479 create thread:1, id:232480    //父进程创建了线程232480
parent:232479 waiting child:232481 exit  //父进程232479等待子进程232481退出
child:232481 enter                       //子进程232481进入
child:232481 exit                        //子进程232481退出
parent:232479 find child:232481 exit     //父进程232479是别到子进程232481退出
parent:232479 waiting thread exit        //父进程232479等待线程退出
pid:232479 exit thread:1, id:232480      //线程232480退出
parent:232479 find thread exit           //父进程是别到线程退出

ps -efL | grep t_thread
UID    PID     PPID    LWP     C    NLWP  STIME TTY      TIME      CMD
user   232479  201990  232479  0    2     21:21 pts/0    00:00:00  ./t_thread
user   232479  201990  232480  0    2     21:21 pts/0    00:00:00  ./t_thread
user   232481  232479  232481  0    1     21:21 pts/0    00:00:00  ./t_thread

父进程232479有两个线程(LWP):232479与232480,他们的NLWP也都是2
子进程232481的父进程是232479,他只有一个线程232481,并且他的NLWP是1

可见一个多线程的程序,在其中一个线程执行fork,只会创建一个子进程,而且这个子进程是个单线程的进程。
举报

相关推荐

0 条评论