clone,fork与pthread_create函数

linux中创建线程和进程的过程非常类似,都是依靠 clone 函数来实现;

也就是说,只需要一个 clone函数,就既能创建进程,又能创建线程;

其中线程创建使用pthread_create函数,进程创建使用fork函数;

其实clone和fork的主要差别是传递了几个參数。

创建进程:clone(SIGCHLD)

创建线程:clone(CLONE_VM | CLONE_FS | CLONE_FILES | SIGCHLD)

linux 内核没有严格区分线程和进程,线程其实被视为一个与其他进程共享某些资源的进程,看起来就像是一个轻量级的进程。

clone函数原型:

#define _GNU_SOURCE

#include <sched.h>

int clone(int (*fn)(void *), void *stack, int flags, void *arg, ... /* pid_t *parent_tid, void *tls, pid_t *child_tid */ );

long clone3(struct clone_args *cl_args, size_t size);

#include <unistd.h>

pid_t fork(void);

// pid_t是一个宏定义,其实质是 int 被定义在#include <sys/types.h>中,pid_t定义的类型都是进程号类型。范围:0~32767;

// 返回值:若成功调用一次则返回两个值,子进程返回 0,父进程返回子进程PID(

  • 11
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
`clone` 和 `pthread_create` 都是用于在 Linux 系统中创建新线程或进程的函数。它们有以下几点区别: 1. `clone` 可以创建线程和进程,而 `pthread_create` 只能创建线程。 2. `clone` 的参数比 `pthread_create` 更多,可以精细地控制创建的新线程或进程的各项属性。例如,可以指定新线程或进程使用与父进程不同的堆栈空间,或者共享父进程的地址空间。`pthread_create` 的参数相对简单,只需要指定新线程的运行函数即可。 3. `clone` 的返回值是新线程或进程的 ID,而 `pthread_create` 的返回值是一个 `int` 类型的错误码,如果返回 0 表示成功创建新线程,否则表示创建失败。 4. `clone` 更加底层,需要手动管理一些资源,例如堆栈空间。而 `pthread_create` 更加高层,对于资源管理有较好的封装,使用起来更加方便。 下面是 `clone` 和 `pthread_create` 的简单示例代码: 使用 `clone` 创建新线程: ``` #define STACK_SIZE 1024*1024 int thread_func(void* arg) { printf("This is a new thread.\n"); return 0; } int main() { char* stack = malloc(STACK_SIZE); pid_t pid = clone(thread_func, stack + STACK_SIZE, CLONE_VM | SIGCHLD, NULL); if (pid == -1) { printf("Failed to create new thread.\n"); exit(EXIT_FAILURE); } printf("Created new thread with PID %d.\n", pid); waitpid(pid, NULL, 0); free(stack); return 0; } ``` 使用 `pthread_create` 创建新线程: ``` void* thread_func(void* arg) { printf("This is a new thread.\n"); return NULL; } int main() { pthread_t thread_id; int ret = pthread_create(&thread_id, NULL, thread_func, NULL); if (ret != 0) { printf("Failed to create new thread.\n"); exit(EXIT_FAILURE); } printf("Created new thread with ID %ld.\n", thread_id); pthread_join(thread_id, NULL); return 0; } ``` 注:以上示例代码仅为演示如何使用 `clone` 和 `pthread_create` 创建新线程或进程,实际使用时需要根据具体情况进行适当修改。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值