gpt4 book ai didi

c - 将文件描述符传递给线程并在函数中使用它(作业)

转载 作者:太空宇宙 更新时间:2023-11-04 01:36:29 24 4
gpt4 key购买 nike

我的任务是制作打印服务器的精简多线程模型。

函数get_server的原型(prototype)是:

void *get_request(void *arg);

“参数 arg 指向要从中读取请求的打开文件描述符。”因此在测试中建议使用 STDIN_FILENO,但总而言之,描述符需要是通用的。

pthread_create(&tid, &attr, get_request, STDIN_FILENO);

在我尝试使用 arg 的函数中,无法将它从 void * 更改为任何可用的值。例如,这些都不起作用:

read(*arg, intvariable, sizeof(int)); // can't cast void * error
int fd = *arg; // can't cast void * error
int fd = *(int *)arg; // seg fault
int fd = *((int *)arg); // seg fault

int fd = atoi(arg); // seg fault
// yes I'm aware arg isn't a char* but that's
// from the example code we were given

最佳答案

你走对了:

void *get_request(void *arg)
{
int fd = (int) arg;

...
}

但是,这不是推荐的方式。而是创建一个变量并将其地址传递给 pthread_create 调用:

int fd = STDIN_FILENO;
pthread_create(&tid, &attr, get_request, &fd);

然后你使用

void *get_request(void *arg)
{
int fd = *((int *) arg);

...
}

不过要小心,用于 pthread_create 调用的变量范围不会在线程启动之前用完。然后你将有一个指向未使用内存的指针。将此变量放在 main 函数的顶部(如果您在 main 中调用 pthread_create)。

关于c - 将文件描述符传递给线程并在函数中使用它(作业),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13505340/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com