Linux多线程学习(十)pthread_atfork

本文介绍了一个使用pthread_atfork函数的示例程序,演示了如何注册父进程和子进程在fork前后调用的函数。该程序还展示了如何创建文件以记录fork处理程序的执行情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pthread_atfork 注册fork的函数

实例

 #define _UNIX03_THREADS 1
      2 #include <pthread.h>
      3 #include <stdio.h>
      4 #include <unistd.h>
      5 #include <fcntl.h>
      6 #include <sys/types.h>
      7 #include <sys/stat.h>
      8 #include <sys/wait.h>
      9 #include <stdlib.h>
     10 #include <errno.h>
     11
     12 char fn_c[] = "childq.out";
     13 char fn_p[] = "parentside.out";
     14 int  fd_c;
     15 int  fd_p;
     16
     17 void prep1(void)  {
     18   char buff[80] = "prep1\n";
     19   write(4,buff,sizeof(buff));
     20 }
     21
     22 void prep2(void)  {
     23   char buff[80] = "prep2\n";
     24   write(4,buff,sizeof(buff));
     25 }
     26
     27 void prep3(void)  {
     28   char buff[80] = "prep3\n";
     29   write(4,buff,sizeof(buff));
     30 }
     31
     32
     33 void parent1(void)  {
     34   char buff[80] = "parent1\n";
     35   write(4,buff,sizeof(buff));
     36 }
     37
     38 void parent2(void)  {
     39   char buff[80] = "parent2\n";
     40   write(4,buff,sizeof(buff));
     41 }
     42
     43 void parent3(void)  {
     44   char buff[80] = "parent3\n";
     45   write(4,buff,sizeof(buff));
     46 }
     47
     48
     49 void child1(void)  {
     50   char buff[80] = "child1\n";
     51   write(3,buff,sizeof(buff));
     52 }
     53
     54 void child2(void)  {
     55   char buff[80] = "child2\n";
     56   write(3,buff,sizeof(buff));
     57 }
     58
     59 void child3(void)  {

60   char buff[80] = "child3\n";
     61   write(3,buff,sizeof(buff));
     62 }
     63
     64 void *thread1(void *arg) {
     65
     66   printf("Thread1: Hello from the thread.\n");
     67
     68 }
     69
     70
     71 int main(void)
     72 {
     73   pthread_t thid;
     74   int       rc, ret;
     75   pid_t     pid;
     76   int       status;
     77   char   header[30] = "Called Child Handlers\n";
     78
     79
     80   if (pthread_create(&thid, NULL, thread1, NULL) != 0) {
     81     perror("pthread_create() error");
     82     exit(3);
     83   }
     84
     85   if (pthread_join(thid, NULL) != 0) {
     86     perror("pthread_join() error");
     87     exit(5);
     88   } else {
     89     printf("IPT: pthread_join success!  Thread 1 should be finished now.\n");
     90     printf("IPT: Prepare to fork!!!\n");
     91   }
     92
     93
     94   /*-----------------------------------------*/
     95   /*|  Start atfork handler calls in parent  */
     96   /*-----------------------------------------*/
     97   /* Register call 1 */
     98   rc = pthread_atfork(&prep1, &parent2, &child3);
     99 /*  if (rc != 0) {
    100      perror("IPT: pthread_atfork() error [Call #1]");
    101      printf("  rc= %d, errno: %d, ejr: %08x\n", rc, errno, __errno2());
    102   }*/
    103
    104
    105   /* Register call 2 */
    106   rc = pthread_atfork(&prep2, &parent3, &child1);
    107   /*if (rc != 0) {
    108      perror("IPT: pthread_atfork() error [Call #2]");
    109      printf("  rc= %d, errno: %d, ejr: %08x\n", rc, errno, __errno2());

}*/
    111   /* Register call 3 */
    112   rc = pthread_atfork(&prep3, &parent1, NULL);
    113   /*if (rc != 0) {
    114      perror("IPT: pthread_atfork() error [Call #3]");
    115      printf("  rc= %d, errno: %d, ejr: %08x\n", rc, errno, __errno2());
    116   }*/
    117   /* Create output files to expose the execution of fork handlers. */
    118   if ((fd_c = creat(fn_c, S_IWUSR)) < 0)
    119     perror("creat() error");
    120   else
    121     printf("Created %s and assigned fd= %d\n", fn_c, fd_c);
    122   if ((ret = write(fd_c,header,30)) == -1)
    123     perror("write() error");
    124   else
    125     printf("Write() wrote %d bytes in %s\n", ret, fn_c);
    126   if ((fd_p = creat(fn_p, S_IWUSR)) < 0)
    127     perror("creat() error");
    128   else
    129     printf("Created %s and assigned fd= %d\n", fn_p, fd_p);
    130   if ((ret = write(fd_p,header,30)) == -1)
    131     perror("write() error");
    132   else
    133     printf("Write() wrote %d bytes in %s\n", ret, fn_p);
    134   pid = fork();
    135   if (pid < 0)
    136     perror("IPT: fork() error");
    137   else {
    138     if (pid == 0) {
    139       printf("Child: I am the child!\n");
    140       printf("Child: My PID= %d, parent= %d\n", (int)getpid(),
    141               (int)getppid());
    142       exit(0);
    143     } else {
    144       printf("Parent: I am the parent!\n");
    145       printf("Parent: My PID= %d, child PID= %d\n", (int)getpid(), (int)pid);
    146       if (wait(&status) == -1)
    147         perror("Parent: wait() error");
    148       else if (WIFEXITED(status))
    149              printf("Child exited with status: %d\n",WEXITSTATUS(status));
    150            else
    151              printf("Child did not exit successfully\n");
    152     close(fd_c);
    153     close(fd_p);
    154     }
    155   }
    156 }


编译  gcc -o pthread_atfork -pthread pthread_atfork.c

这里注意 -pthread 而不是-lpthread 若是后者则会报错 pthread_atfork函数找不到


运行结果

Thread1: Hello from the thread.
IPT: pthread_join success!  Thread 1 should be finished now.
IPT: Prepare to fork!!!
Created childq.out and assigned fd= 3
Write() wrote 30 bytes in childq.out
Created parentside.out and assigned fd= 4
Write() wrote 30 bytes in parentside.out
Child: I am the child!
Child: My PID= 2616, parent= 2614
Parent: I am the parent!
Parent: My PID= 2614, child PID= 2616
Child exited with status: 0

<think>好的,用户想了解Linux下线程的使用与实现。首先,我需要整理一下用户提供的引用内容,看看这些引用中有哪些关键点。根据引用[1],Linux中没有内核级别的线程接口,而是通过用户层的pthread库来模拟线程,封装了轻量级进程的系统调用。引用[2]提到Linux用struct TCB结构体描述线程,并需要将线程和进程解耦,同时设计调度算法。引用[3]和[4]涉及线程分离函数和线程安全等问题。 用户的问题集中在Linux线程的使用和实现,所以回答需要涵盖这两个方面。首先,应该解释线程在Linux中的实现方式,即基于轻量级进程,用户层的pthread库封装系统调用。然后,讨论线程的管理,比如TCB结构体和调度。接着,使用方法部分需要包括创建线程、终止、同步机制(互斥锁、信号量)等。此外,线程安全和注意事项,比如避免在多线程中调用fork,以及线程分离函数pthread_detach的使用也很重要。 需要确保回答结构清晰,分点说明实现和使用,并引用提供的参考资料。同时,根据系统指令,数学公式要用$...$,独立公式用$$...$$,但在这个问题中可能用不上太多数学公式,不过如果有涉及的话需要注意格式。生成的相关问题要围绕线程的实现细节、使用方法、常见问题展开。 检查是否有遗漏的关键点,比如线程与进程的关系,线程的优缺点,以及实际应用中的注意事项。确保每个部分都有对应的引用支持,比如引用[1]说明pthread库的作用,引用[2]解释线程管理和调度,引用[3]和[4]涉及具体函数和线程安全。 最后,生成的相关问题需要引导用户深入理解线程的实现机制、使用方法和常见问题处理,比如线程与进程的区别、线程私有数据、线程池的实现等。确保问题覆盖用户可能感兴趣的各个方面。</think>### Linux线程的实现与使用 #### 一、Linux线程的实现机制 1. **用户层与内核的关系** 在Linux中,线程通过用户层的**原生线程库pthread**实现[^1]。内核本身没有直接提供线程接口,而是通过轻量级进程(LWP)模拟线程行为。pthread库封装了系统调用(如`clone()`),将线程创建、同步等操作转化为对LWP的管理。 2. **线程描述与组织** 内核通过`struct task_struct`描述进程/线程,而用户层线程库(如pthread)维护额外的数据结构(类似`struct TCB`)来记录线程属性(如栈、局部存储)[^2]。线程组内的所有线程共享进程资源(如地址空间、文件描述符),但拥有独立的执行流和栈空间。 3. **线程调度** Linux线程调度由内核负责,采用与进程相同的调度算法(如CFS)。线程的优先级、时间片等属性通过系统调用设置,例如: ```c pthread_setschedparam(pthread_t thread, int policy, const struct sched_param *param); ``` #### 二、线程的基本使用 1. **线程创建** 使用`pthread_create`接口创建线程,需指定线程函数和参数: ```c #include <pthread.h> int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void*), void *arg); ``` - 示例:主线程创建子线程 ```c void* thread_func(void* arg) { printf("Thread ID: %ld\n", (long)pthread_self()); return NULL; } pthread_t tid; pthread_create(&tid, NULL, thread_func, NULL); ``` 2. **线程终止** - 线程函数返回时自动终止。 - 调用`pthread_exit`显式退出: ```c void pthread_exit(void *retval); ``` 3. **线程同步** - **互斥锁(Mutex)** 避免多线程访问共享资源冲突: ```c pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; pthread_mutex_lock(&mutex); // 临界区操作 pthread_mutex_unlock(&mutex); ``` - **信号量(Semaphore)** 控制资源访问数量: ```c sem_t sem; sem_init(&sem, 0, 1); // 初始值为1 sem_wait(&sem); // P操作 sem_post(&sem); // V操作 ``` 4. **线程分离** 默认线程为可连接(joinable),需通过`pthread_join`回收资源。若无需等待线程结束,可调用`pthread_detach`分离线程[^3]: ```c pthread_detach(pthread_self()); // 线程自行分离 ``` #### 三、关键问题与注意事项 1. **线程安全与竞争条件** 多线程操作全局变量或共享资源时需同步。例如,多个线程对同一变量累加可能因竞争导致结果错误[^4]。 2. **线程与`fork()`的冲突** `fork()`会复制调用线程的执行状态,但其他线程不会被复制。若父线程持有锁,子进程可能死锁。解决方式: - 调用`pthread_atfork`注册预处理函数。 - 避免在多线程程序中使用`fork()`[^4]。 3. **线程局部存储(TLS)** 使用`pthread_key_create`定义线程私有数据: ```c pthread_key_t key; pthread_key_create(&key, NULL); pthread_setspecific(key, data_ptr); // 设置线程私有数据 void* data = pthread_getspecific(key); // 获取数据 ``` #### 四、线程的优缺点 | 优点 | 缺点 | |------|------| | 轻量级上下文切换 | 调试复杂度高 | | 共享内存提升通信效率 | 需严格处理同步问题 | | 适合I/O密集型任务 | 线程崩溃可能导致进程退出 |
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值