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
You are on the right way:
However, it’s not the recommended way. Instead create a variable and pass the address of that to the
pthread_createcall:Then you use
Be careful though, so the scope of the variable used for the
pthread_createcall doesn’t run out before the thread starts. Then you will have a pointer to unused memory. Put this variable at the top of themainfunction (if you are callingpthread_createinmain).