解决方案:Linux 下使用clone()函数 ,编译后出现CLONE_VM未定义的错误

博客指出在使用clone函数时,要在代码开始(顶部)处引入一个宏和头文件,这是使用该函数的关键操作,属于编程相关的信息技术内容。

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

在使用clone函数时,需要在代码的开始(顶部)处引入一个宏和头文件,如下

#define _GNU_SOURCE   /*注意摆放位置*/         
#include <sched.h>   /*注意摆放位置*/   
#include<sys/types.h>
#include<sys/syscall.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
//  Linux下一个函数调用栈 2页 8kb
#define FIBER_STACK 8192
int do_something(void* s)
{
  printf(" pid = %d,LWP id = %lu",getpid(),syscall(SYS_gettid));
  return 0;
}
int main()
{
 void* stack;
 stack = malloc(FIBER_STACK);
                     /*栈顶在高地址处,向下生长*/
 clone(do_something,(char*)stack+FIBER_STACK,CLONE_VM|CLONE_VFORK,NULL);
}

“`

#define _GNU_SOURCE #include “sched.h” #include<sys/types.h> #include<sys/syscall.h> #include<unistd.h> #include <pthread.h> #include “stdio.h” #include “stdlib.h” #include “semaphore.h” #include “sys/wait.h” #include “string.h” int producer(void * args); int consumer(void * args); pthread_mutex_t mutex; sem_t product; sem_t warehouse; char buffer[8][4]; int bp=0; int main(int argc,char** argv) { pthread_mutex_init(&mutex,NULL); sem_init(&product,0,0); sem_init(&warehouse,0,8); int clone_flag,arg,retval; char stack; clone_flag=CLONE_VM|CLONE_SIGHAND|CLONE_FS| CLONE_FILES; int i; for(i=0;i<2;i++) { //创建四个线程 arg = i; stack =(char)malloc(4096); retval=clone((void*)producer,&(stack[4095]),clone_flag, (void*)&arg); stack =(char*)malloc(4096); retval=clone((void*)consumer,&(stack[4095]),clone_flag, (void*)&arg); //usleep(1000); usleep(1); } exit(1); } int producer(void* args) { int id = ((int)args); int i; for(i=0;i<10;i++) { sleep(i+1); //表现线程速度差别 sem_wait(&warehouse); pthread_mutex_lock(&mutex); if(id==0) strcpy(buffer[bp],“aaa\0”); else strcpy(buffer[bp],“bbb\0”); bp++; printf(“producer%d produce %s in %d\n”,id,buffer[bp-1],bp-1); pthread_mutex_unlock(&mutex); sem_post(&product); } printf(“producer%d is over!\n”,id); } int consumer(void *args) { int id = ((int)args); int i; for(i=0;i<10;i++) { sleep(10-i); //表现线程速度差别 sem_wait(&product); pthread_mutex_lock(&mutex); bp–; printf(“consumer%d get %s in %d\n”,id,buffer[bp],bp+1); strcpy(buffer[bp],“zzz\0”); pthread_mutex_unlock(&mutex); sem_post(&warehouse); } printf(“consumer%d is over!\n”,id); } 保持运行后的输出和基本功能不变,修改代码,解决使用gcc -pthread clone.c -o clone.out命令运行后似乎处于死循环,consumer1 is over!无法显示的bug(禁止修改gcc指令,根据gcc指令进行修改)
最新发布
05-14
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值