215k views
1 vote
Implementing doServer(int listenFd):

doServer() should have a loop in which it waits for a client to connect to listenFd. When a client does, it should:

malloc() enough memory for 2 integers
put the file descriptor from accept() in one of those spaces
put the value of threadCount in the other space, and increment threadCount
Make a detached thread to handle this new client. I called my function handleClient(), but you may call yours whatever. Pass the address of your malloc()-ed array.
The loop should then go back for another accept().

// PURPOSE: To run the server by 'accept()'-ing client requests from
// 'listenFd' and doing them.
void doServer (int listenFd
)
{
// I. Application validity check:

// II. Server clients:
pthread_t threadId;
pthread_attr_t threadAttr;
int threadCount = 0;

// YOUR CODE HERE:

while (1)
{
int* clientFdPtr = (int*)malloc(2*sizeof(int));

// YOUR CODE HERE:
}

pthread_attr_destroy(&threadAttr);

// III. Finished:
}

1 Answer

5 votes

Final answer:

The student's question involves implementing a server-side function in C to handle client connections using threads, require dynamic memory allocation, and proper thread management.

Step-by-step explanation:

The student is asking about how to implement a server-side function in C which handles incoming client connections using threads. The key steps that need to be incorporated into the doServer function include waiting for client connections, dynamically allocating memory to store client information, creating and managing threads, and proper memory handling. Here's a snippet of the required C code:

void doServer(int listenFd) {
pthread_t threadId;
pthread_attr_t threadAttr;
pthread_attr_init(&threadAttr);
pthread_attr_setdetachstate(&threadAttr, PTHREAD_CREATE_DETACHED);
int threadCount = 0;

while (1) {
int* clientFdPtr = (int*)malloc(2*sizeof(int));
if (clientFdPtr == NULL) {
// Handle memory allocation failure
continue;
}
clientFdPtr[0] = accept(listenFd, NULL, NULL);
if (clientFdPtr[0] == -1) {
// Handle accept failure
free(clientFdPtr);
continue;
}
clientFdPtr[1] = threadCount++;

if (pthread_create(&threadId, &threadAttr, handleClient, (void *)clientFdPtr) != 0) {
// Handle thread creation failure
free(clientFdPtr);
}
}
pthread_attr_destroy(&threadAttr);
}

This script will continually accept new connections, allocate memory for client data, increment the threadCount, and create a new detached thread to process the client request by passing in the allocated memory which contains both the client's file descriptor and the count indicator.

User Steven McConnon
by
8.5k points