I'm trying to make a server program that uses sockets and threads. I can get it to compile, but it keeps giving me a segmentation fault. I've made a number of changes to the program, and have no idea what is causing it. If anyone has an idea, please let me know. Here's the code, followed by the output i get. (Compiled using gcc) I've gotten the client code to work with the server code before I added the threads, but not now.
Code:
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <netinet/in.h>
#include <signal.h>
#include <unistd.h>
#include <pthread.h>
void *thread_function(void *arg);
int main ()
{
int res; /* for error checking */
pthread_t client;
void *thread_result;
int j = 0; /* counter */
int server_sockfd, client_sockfd;
int server_len, client_len;
struct sockaddr_in server_address;
struct sockaddr_in client_address;
server_sockfd = socket(AF_INET, SOCK_STREAM, 0);
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(9734);
server_len = sizeof(server_address);
bind(server_sockfd, (struct sockaddr *)&server_address, server_len);
listen(server_sockfd, 5);
signal(SIGCHLD, SIG_IGN);
while(1) {
client_len = sizeof(client_address);
client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
printf("client_sockfd after accept call: %d\n", client_sockfd);
if(client_sockfd < 0) {
perror("server: accept error");
exit(1);
}
printf("fixin to create pthread\n");
res = pthread_create(&client, NULL, thread_function, (void *) client_sockfd);
if(res != 0) {
perror("Thread creation failed");
exit(1);
}
printf("pthread created\n");
res = pthread_join(client, &thread_result);
printf("pthread joined?\n");
if(res != 0) {
perror("Thread join failed");
exit(1);
}
printf("pthread joined.\n");
}
}
void *thread_function(void *arg)
{
char ch;
int sockfd;
printf("inside thread_function\n");
sockfd = *((int *)arg);
printf("client_sockfd assigned: %d\n", sockfd);
read(sockfd, &ch, 1);
printf("char read: %c\n", ch);
sleep(1);
ch++;
write(sockfd, &ch, 1);
printf("char sent: %c\n", ch);
close(sockfd);
pthread_exit(1);
}
output:
client_sockfd after accept call: 4
fixin to create pthread
inside thread_function
pthread created
char from server = z
[1]+ Segmentation fault ./server4.exe
(client code)
Code:
#include<sys/types.h>
#include<sys/socket.h>
#include<stdio.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<unistd.h>
int main()
{
int sockfd;
int len;
struct sockaddr_in address;
int result;
char ch = 'A';
sockfd = socket(AF_INET, SOCK_STREAM, 0);
address.sin_family = AF_INET;
address.sin_addr.s_addr = inet_addr("127.0.0.1");
address.sin_port = htons(9734);
len = sizeof(address);
result = connect(sockfd, (struct sockaddr *)&address, len);
if(result == -1) {
perror("client1");
exit(1);
}
write(sockfd, &ch, 1);
ch = 'z';
read(sockfd, &ch, 1);
printf("char from server: %c\n", ch);
close(sockfd);
exit(0);
}