linux两种clone模式,《Linux系统调用: clone用法》

一、程序

#define _GNU_SOURCE

#include

#include

#include

#include

#include

#include

#include

#include

int param = 0;

int thread_fn(void *data)

{

int j;

printf("starting child thread_fn, pid=%d\n", getpid());

for (j = 0; j < 10; j++) {

param = j + 1000;

sleep(1);

printf("child thread running: j=%d, param=%d secs,ppid = %d\n", j,

param,getppid());

}

printf("child thread_fn exit\n");

return 0;

}

int main(int argc, char **argv)

{

int j, tid, pagesize, stacksize;

void *stack;

printf("starting parent process, pid=%d\n", getpid());

pagesize = getpagesize();

stacksize = 4 * pagesize;

/* could probably just use malloc(), but this is safer */

/* stack = (char *)memalign (pagesize, stacksize); */

posix_memalign(&stack, pagesize, stacksize);

printf("Setting a clone child thread with stacksize = %d....", stacksize);

tid = clone(thread_fn, (char *)stack + stacksize, CLONE_VM | SIGCHLD, 0);

printf(" with tid=%d\n", tid);

if (tid < 0)

exit(EXIT_FAILURE);

/* could do a wait (&status) here if required */

for (j = 0; j < 6; j++) {

param = j;

sleep(1);

printf("parent running: j=%d, param=%d secs\n", j,

param);

}

printf("parent killitself\n");

/* We shouldn't free(stack) here since the child using it is still running */

exit(EXIT_SUCCESS);

}

编译: arm-linux-gnueabi-gcc clone_test.c  -o clone_test --static

运行:

/ # /mnt/clone_test

starting parent process, pid=777

Setting a clone child thread with stacksize = 16384.... with tid=778

starting child thread_fn, pid=778

parent running: j=0, param=1000 secs

child thread running: j=0, param=1 secs,ppid = 777

parent running: j=1, param=1001 secs

child thread running: j=1, param=2 secs,ppid = 777

parent running: j=2, param=1002 secs

child thread running: j=2, param=3 secs,ppid = 777

parent running: j=3, param=1003 secs

child thread running: j=3, param=4 secs,ppid = 777

parent running: j=4, param=1004 secs

child thread running: j=4, param=5 secs,ppid = 777

parent running: j=5, param=1005 secs

parent killitself

/ # child thread running: j=5, param=1005 secs,ppid = 1

child thread running: j=6, param=1006 secs,ppid = 1

child thread running: j=7, param=1007 secs,ppid = 1

child thread running: j=8, param=1008 secs,ppid = 1

child thread running: j=9, param=1009 secs,ppid = 1

child thread_fn exit

标签:parent,thread,clone,child,secs,param,用法,running,Linux

来源: https://blog.csdn.net/yexiangCSDN/article/details/96863499

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值