Linux 中使用 clone 函数来创建线程

    Linux 上创建线程一般使用的是 pthread 库  实际上 libc 也给我们提供了创建线程的函数  那就是 clone

       int clone(int (*fn)(void *), void *child_stack,
                 int flags, void *arg, ...
                 /* pid_t *ptid, struct user_desc *tls, pid_t *ctid */ );

man 手册里面说的很清楚这个函数存在的意义就是实现 线程  当然这个函数不是 linux 的系统调用 而是对系统调用的封装 。    

    首先需要给新的线程创建个堆栈 ,使用函数 mmap ,这个函数常用来完成文件映射  这里分配内存也是可以的

    void *pstack = (void *)mmap(NULL,
                                STACK_SIZE,
                                PROT_READ | PROT_WRITE ,
                                MAP_PRIVATE | MAP_ANONYMOUS | MAP_ANON ,//| MAP_GROWSDOWN ,
                                -1,
                                0);

通过指定  MAP_ANONYMOUS 标识  系统就不会创建文件映射 而仅仅分配内存

注意堆栈不要太小了  不然会溢出的 。。

然后调用 clone 函数

1ret = clone(thread_func, 2 (void *)((unsigned char *)pstack + STACK_SIZE), 3 CLONE_VM | CLONE_FS | CLONE_THREAD | CLONE_FILES | CLONE_SIGHAND | SIGCHLD, 4 (void *)NULL);

注意堆栈是向下增长的  所以指定对战的内存的时候 要使用分配内存的尾部的指针

几个标识的意义

1CLONE_VM (0x100) - tells the kernel to let the original process and the clone in the same memory space; 2 CLONE_FS (0x200) - both get the same file system information; 3 CLONE_FILES (0x400) - share file descriptors; 4 CLONE_SIGHAND (0x800) - both processes share the same signal handlers; 5 CLONE_THREAD (0x10000) - this tells the kernel, that both processes would belong to the same thread group (be threads within the same process);

  在线程函数中 直接  return 就可以退出线程了。。。。

  使用 clone 的时候 指定 CLONE_THREAD 那么以后就不能使用 wait 来等待这个线程了 相当于 deteched .了。。。查看man 手册可以看到

A new thread created with CLONE_THREAD has the same parent process as the caller of clone() (i.e., like CLONE_PARENT), so that calls  to getppid(2)  return the same value for all of the threads in a thread group.  When a CLONE_THREAD thread terminates, the thread that created it using clone() is not sent a SIGCHLD (or other termination) signal; nor can the  status  of  such  a  thread  be  obtained  using wait(2).  (The thread is said to be detached.)

下面是我测试的代码

1#define _GNU_SOURCE /* or _BSD_SOURCE or _SVID_SOURCE */ 2#include <unistd.h> 3#include <sys/syscall.h> /* For SYS_xxx definitions */ 4#include <sys/types.h> 5#include <sched.h> 6#include <sys/mman.h> 7#include <signal.h> 8#include <stdio.h> 9#include <errno.h> 10#include <string.h> 11#include <sys/wait.h> 12 13#define STACK_SIZE 1024*1024*8 //8M 14 15int thread_func(void *lparam) 16{ 17 printf("thread id %d \n", (int)syscall(SYS_gettid)); 18 printf("thread get param : %d \n", (int)lparam); 19 sleep(1); 20 return 0; 21} 22 23 24void child_handler(int sig) 25{ 26 printf("I got a SIGCHLD\n"); 27} 28 29int main(int argc, char **argv) 30{ 31 setvbuf(stdout, NULL, _IONBF, 0); 32 signal(SIGCHLD, child_handler); 33 //signal(SIGUSR1, SIG_IGN); 34 35 void *pstack = (void *)mmap(NULL, 36 STACK_SIZE, 37 PROT_READ | PROT_WRITE , 38 MAP_PRIVATE | MAP_ANONYMOUS | MAP_ANON ,//| MAP_GROWSDOWN , 39 -1, 40 0); 41 if (MAP_FAILED != pstack) 42 { 43 int ret; 44 printf("strace addr : 0x%X\n", (int)pstack); 45 /* 46 CLONE_VM (0x100) - tells the kernel to let the original process and the clone in the same memory space; 47 CLONE_FS (0x200) - both get the same file system information; 48 CLONE_FILES (0x400) - share file descriptors; 49 CLONE_SIGHAND (0x800) - both processes share the same signal handlers; 50 CLONE_THREAD (0x10000) - this tells the kernel, that both processes would belong to the same thread group (be threads within the same process); 51 */ 52 ret = clone(thread_func, 53 (void *)((unsigned char *)pstack + STACK_SIZE), 54 CLONE_VM | CLONE_FS | CLONE_FILES | CLONE_SIGHAND |SIGCHLD, 55 (void *)NULL); 56 if (-1 != ret) 57 { 58 pid_t pid = 0; 59 printf("start thread %d \n", ret); 60 sleep(5); 61 pid = waitpid(-1, NULL, __WCLONE | __WALL); 62 printf("child : %d exit %s\n", pid,strerror(errno)); 63 } 64 else 65 { 66 printf("clone failed %s\n", strerror(errno) ); 67 } 68 } 69 else 70 { 71 printf("mmap() failed %s\n", strerror(errno)); 72 } 73 return 0; 74}
点赞
收藏

评论区

加载中...

相关推荐

MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1

文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s

Oracle 分组与拼接字符串同时使用

SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(

MySQL部分从库上面因为大量的临时表tmp_table造成慢查询

背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_

皕杰报表之UUID

​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为

手写Java HashMap源码

HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22

2020年前端实用代码段,为你的工作保驾护航

有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )