Reputation: 320
My assignment is to do a stripped down multi-threaded mockup of a print server.
The function get_server's prototype is:
void *get_request(void *arg);
"The parameter arg points to an open file descriptor from where the request is to be read." So in testing it's recommended to use STDIN_FILENO, but the descriptor needs to be generic when all is said and done.
pthread_create(&tid, &attr, get_request, STDIN_FILENO);
Inside the function I'm trying to use arg, and can't change it from a void * to anything usable. For instance none of this works:
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
Upvotes: 1
Views: 6013
Reputation: 37930
Your function expects a pointer to a value, but you are passing the value itself! So to follow the pointer scheme, you need to pass a pointer to a global variable that contains the value STDIN_FILENO
.
Or alternatively, you can "cheat" by passing STDIN_FILENO
like you're currently doing, and then cast the void*
to a simple int
(not a pointer!) and use it as is:
int fd = (int) arg;
Upvotes: 0
Reputation: 409176
You are on the right way:
void *get_request(void *arg)
{
int fd = (int) arg;
...
}
However, it's not the recommended way. Instead create a variable and pass the address of that to the pthread_create
call:
int fd = STDIN_FILENO;
pthread_create(&tid, &attr, get_request, &fd);
Then you use
void *get_request(void *arg)
{
int fd = *((int *) arg);
...
}
Be careful though, so the scope of the variable used for the pthread_create
call doesn't run out before the thread starts. Then you will have a pointer to unused memory. Put this variable at the top of the main
function (if you are calling pthread_create
in main
).
Upvotes: 4