Goal: I am trying to write a concurrent TCP server that accepts and responds to multiple client connection requests, each requesting a file transfer.
I think the error lies within the file handling section in start_routine(), need to verify where. (Read more below code)
File: server.c
#define CONNECTIONS 5
FILE *input;
pthread_t tids[CONNECTIONS];
char name[100];
char buff[1024]; //buffer size
void *start_routine(void *arg)
{
//recv file request
read((int) arg, name, sizeof(name));
//file handling
input = fopen(name, "rb");
printf("hi\n"); //testing
while (!feof(input))
write((int) arg, buff, fread(buff, sizeof(char), sizeof(buff), input));
return NULL;
}
int main(int argc, char *argv[])
{
struct sockaddr_in serv_addr;
if (argc != 2)
{
printf("Usage: ./a.out <port #>\n");
exit(0);
}
//open socket
int listenfd = socket(AF_INET, SOCK_STREAM, 0);
//init sockaddr_in struct
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[1]));
serv_addr.sin_addr.s_addr = htons(INADDR_ANY);
//binds listenfd to a specific sockaddr_in
bind(listenfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
for(int i = 0; i <= CONNECTIONS; i++){
//listen for new connections on listenfd
listen(listenfd, CONNECTIONS);
//accepts a connection
int connfd = accept(listenfd, (struct sockaddr *)NULL, NULL);
pthread_create(tids, NULL, start_routine, &connfd);
}
//cleaning
close(listenfd);
fclose(input);
return 0;
}
File: client.c
int main(int argc, char *argv[])
{
int n;
char buff[1024]; //buffer size
struct sockaddr_in serv_addr;
if (argc != 4)
{
printf("Usage: ./a.out <file required> <ip of server> <port #> \n");
exit(0);
}
//open socket
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
//init sockaddr_in struct
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[3]));
serv_addr.sin_addr.s_addr = inet_addr(argv[2]);
//connect to <server_ip>: <port>
connect(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
//file handling
FILE *request;
request = fopen("dst.txt", "wb");
//send file request
write(sockfd, argv[1], strlen(argv[1]) + 1);
while ((n = read(sockfd, buff, sizeof(buff))) > 0)
fwrite(buff, sizeof(char), n, request);
//cleaning
fclose(request);
close(sockfd);
return 0;
}
Other files in folder: src.txt
Compiled Using:
gcc server.c -o server -lpthread
./server 8080
gcc client.c -o client
./client src.txt 127.0.0.1 8080
(5 copies of client and so compiled each [client1, client2 ... client5] 5 times)
Problem: Results in segmentation fault. :(
While testing out, I found out that the segmentation fault lies within the start_routine(), in the while loop.
I have used the same snippet from another program (only the variables updated) -- need to know where am I going wrong!
Also, for multi-threading, I created copies of the client program to simulate 5 connections to the server. Hope it is the right way.
Appreciate the help!