如何将参数传递给clone()调用的函数?
我必须在main函数中使用clone()系统调用来获得2个线程。(我知道,还有其他选项,但在本例中,它必须是clone() 系统调用工作,两个线程都到达指定的函数(foo)。但在这个函数中,我需要它们调用另一个具有此签名的函数:如何将参数传递给clone()调用的函数?,c,parameters,clone,C,Parameters,Clone,我必须在main函数中使用clone()系统调用来获得2个线程。(我知道,还有其他选项,但在本例中,它必须是clone() 系统调用工作,两个线程都到达指定的函数(foo)。但在这个函数中,我需要它们调用另一个具有此签名的函数: void increment(int* a, int b) (旁注:它将b*1添加到a.(=a+b)) 重要的是,a和b都在main函数中声明,我不知道如何将它们传递给foo 我已经尝试过不同的事情,但没有成功。我得到一个提示:使用适配器。 但我不知道怎么做。(我也不
void increment(int* a, int b)
(旁注:它将b*1添加到a.(=a+b))
重要的是,a和b都在main函数中声明,我不知道如何将它们传递给foo
我已经尝试过不同的事情,但没有成功。我得到一个提示:使用适配器。
但我不知道怎么做。(我也不知道如何在带有int的clone中使用args。)
有什么建议吗?克隆()的参数之一是
void*arg
。这允许您向函数传递一个空指针。为了传递int指针和int,您必须创建一个结构,将int指针和int分别分配给a
和b
,然后将指向该结构的指针强制转换为空指针。然后在函数内部,您可以反转该过程
我的C有点生疏,我还没有编译这个,所以不要引用我的话,但它应该大致如下:
struct clone_args {
int* a;
int b
};
int main(int argc, char* argv[])
{
struct clone_args args;
args.a = a;
args.b = b;
void* arg = (void*)&args;
clone(fn, ..., arg, ...);
}
int fn(void* arg)
{
struct clone_args *args = (struct clone_args*)arg;
int* a = args->a;
int b = args->b;
}
注意:在调用
fn
时,请注意您创建的结构仍在作用域中,因为它不会被复制。您可能必须malloc
it.以下是示例代码:
#define stacksize 1048576
typedef struct
{
int ii;
int jj;
} someinput1;
static int /* Start function for cloned child */
childFunc(someinput1 *struc)
{
printf("Child: PID=%ld PPID=%ld\n", (long) getpid(), (long) getppid());
printf("Hi!! I am child process created by Clone %ld \n",(long) getpid());
printf("Value of x %d %d\n",struc->ii,struc->jj);
}
int main()
{
someinput1 inputtest;
int i;
char *stack; /* Start of stack buffer */
char *stack1; /* End of stack buffer */
pid_t pid;
stack = malloc(stacksize);
stack1 = stack + stacksize;
for (i = 0;i<5;i++)
{
inputtest.ii = i+5;
inputtest.jj = inputtest.ii + 10;
pid = clone(childFunc, stack1, NULL, (void *) (&inputtest));
printf("clone returned -- %ld \n", (long) pid);
}
sleep(1);
exit(EXIT_SUCCESS);
}
#定义堆栈大小1048576
类型定义结构
{
int ii;
int jj;
}一些输入1;
克隆子级的静态int/*Start函数*/
childFunc(someinput1*struc)
{
printf(“Child:PID=%ld PPID=%ld\n”,(long)getpid(),(long)getppid());
printf(“嗨!!我是克隆%ld\n创建的子进程,(long)getpid());
printf(“x%d%d\n的值”,struc->ii,struc->jj);
}
int main()
{
someinput1输入测试;
int i;
char*堆栈;/*堆栈缓冲区的开始*/
char*stack1;/*堆栈结束缓冲区*/
pid_t pid;
堆栈=malloc(堆栈大小);
stack1=堆栈+堆栈大小;
for(i=0;看,谢谢。最大的麻烦是以某种方式将信息获取到该空指针中。我明天将尝试此操作(现在已经晚了)。请注意,该示例有点危险,main可能会在fn
运行之前返回,因此堆栈上的克隆参数可能会消失。