Multithreaded client-server chat application in c language - c

I wrote an application for communicating between two clients (one will run the server.c application, and the other one client.c).
Everything goes very good at this point, both sides (client and server) can send and receive messages (there are two processes in both sides: one for listening and printing messages, and one for receiving and sending back messages).
There is what I got so far:
client.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <signal.h>
#include "aes.h"
#define BSIZE 320
uint8_t key[] = "qwertyuioplkjhg";
uint8_t iv[] = "123456789098765";
void error(const char *msg) {
perror(msg);
exit(0);
}
int main(int argc, char *argv[]) {
int sockfd, portno, n, pid;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[BSIZE];
char paddedData[BSIZE];
unsigned char crypted_data[BSIZE];
if (argc < 3) {
fprintf(stderr,"usage %s <hostname> <port>\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
error("ERROR opening socket");
}
server = gethostbyname(argv[1]);
if (server == NULL) {
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if(connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) {
error("ERROR connecting");
}
//while(1) {
switch(pid = fork()) {
case -1:
error("ERROR fork");
case 0:
while(1) {
//printf("Please enter the message: ");
bzero(buffer, BSIZE);
//printf("Message: ");
fgets(buffer, BSIZE - 1, stdin);
strncpy(paddedData, buffer, BSIZE);
AES128_CBC_encrypt_buffer(crypted_data, (unsigned char*)paddedData, BSIZE, key, iv);
n = write(sockfd, crypted_data, BSIZE - 1);
if(n < 0) {
error("ERROR writing to socket");
}
}
default:
while(1) {
//bzero(buffer,256);
n = read(sockfd, buffer, BSIZE - 1);
AES128_CBC_decrypt_buffer((unsigned char*)paddedData, (unsigned char*)buffer, BSIZE, key, iv);
if(n < 0) {
error("ERROR reading from socket");
}
printf("<<server>>: %s", paddedData);
}
}
close(sockfd);
return 0;
}
and server.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include "aes.h"
#define BSIZE 320
uint8_t key[] = "qwertyuioplkjhg";
uint8_t iv[] = "123456789098765";
int numberOfConnections = 0;
void communications_handler(int);
void error(const char *msg) {
perror(msg);
exit(1);
}
int main(int argc, char *argv[]) {
int sockfd, newsockfd, portno, pid;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
if(argc < 2) {
fprintf(stderr, "ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) {
error("ERROR opening socket");
}
bzero((char*)&serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if(bind(sockfd, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) < 0) {
error("ERROR on binding");
}
listen(sockfd, 5);
clilen = sizeof(cli_addr);
while(1) {
/* [1] */
newsockfd = accept(sockfd, (struct sockaddr*)&cli_addr, &clilen);
numberOfConnections++;
printf("\nThere are %d clients connected!\n\n", numberOfConnections);
if (newsockfd < 0) {
error("ERROR on accept");
}
pid = fork();
if (pid < 0) {
error("ERROR on fork");
}
if (pid == 0) {
close(sockfd);
communications_handler(newsockfd);
exit(0);
}
else {
close(newsockfd);
}
}
close(sockfd);
return 0;
}
void communications_handler(int sock) {
int n, pid;
char buffer[BSIZE];
char paddedData[BSIZE];
unsigned char crypted_data[BSIZE];
switch(pid = fork()) {
case -1:
error("ERROR on fork");
case 0:
while(1) {
n = read(sock, buffer, BSIZE - 1);
AES128_CBC_decrypt_buffer((unsigned char*)paddedData, (unsigned char*)buffer, BSIZE, key, iv);
if(n < 0) {
error("ERROR reading from socket");
}
printf("<<client>>: %s", paddedData);
}
default:
while(1) {
bzero(buffer, BSIZE);
//printf("Message: ");
fgets(buffer, BSIZE - 1, stdin);
strncpy(paddedData, buffer, BSIZE);
AES128_CBC_encrypt_buffer(crypted_data, (unsigned char*)paddedData, BSIZE, key, iv);
for(int i = 0; i < numberOfConnections; i++) {
n = write(sock, crypted_data, BSIZE - 1);
}
if(n < 0) {
error("ERROR writing to socket");
}
}
}
}
Now I want to extend this program, by letting the server to accept multiple connections (I actually did this, in server.c, at [1]).
But there is now one problem: How can I implement the communication between two (or more) clients (the server will only accept new connections, read data from all connected clients, and send data back to all clients).
Can this be done with processes?

Have a look at Beej's guide to non-blocking socket programming: http://beej.us/guide/bgnet/output/html/singlepage/bgnet.html#select

Related

Server accepts messages but not commands in C

I currently trying to create a program that you can connect from anywhere via the internet using sockets. I obviously want to execute commands and display the output to the client but also want to return anything that the client typed and if it was received, display message reveived. My problem is that even though it displays what was send, it doesn't execute commands. I have tryied to use gdb with break lines inide the while loop but they don't work as if the while loop is never executed.
Server:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
void error(const char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, pid;
socklen_t clilen;
char buffer[256];
char* comm[20],*cbuff;
struct sockaddr_in serv_addr, cli_addr;
int n,i;
char str[INET_ADDRSTRLEN];
char* args;
if (argc < 2)
{
fprintf(stderr, "No port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
memset((char *) &serv_addr, 0, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd,(struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
error("ERROR on binding");
for(;;){
listen(sockfd, 5);
clilen = sizeof(cli_addr);
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
if (inet_ntop(AF_INET, &cli_addr.sin_addr, str, INET_ADDRSTRLEN) == NULL) {
fprintf(stderr, "Could not convert byte to address\n");
exit(1);
}
fprintf(stdout, "The client address is :%s\n", str);
while(1){
bzero(buffer, 256);
n = read(newsockfd, buffer, 255);
if (n < 0) error("ERROR reading from socket");
if(buffer=="exit"){
printf("Exiting...\n");
break;
}
cbuff=strtok(buffer," ");
i=0;
while(cbuff!=NULL){
cbuff=strtok(NULL," ");
comm[i]=cbuff;
i++;
}
if ((pid=fork())==-1){
perror("fork");
}
if(pid!=0){
wait(NULL);
}
else{
dup2(newsockfd,1);
printf("executing...\n");
execvp(comm[0],comm);
perror("execvp");
exit(EXIT_FAILURE);
}
printf("Here is the message: %s\n", buffer);
n = write(newsockfd, "message received", 17);
if (n < 0) error("ERROR writing to socket");
}
break;
}
close(newsockfd);
close(sockfd);
return 0;
}
Client:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg){
perror(msg);
exit(0);
}
int main(int argc, char *argv[]){
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[256];
if (argc < 3){
fprintf(stderr, "usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL){
fprintf(stderr, "ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr,
(char *)&serv_addr.sin_addr.s_addr,server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
do{
printf("Please enter the message: ");
bzero(buffer, 256);
fgets(buffer, 255, stdin);
if(buffer=="exit"){
printf("Exiting...\n");
break;
}
n = write(sockfd, buffer, strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer, 256);
n = read(sockfd, buffer, 255);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n", buffer);
}while(1);
return 0;
}

TCP/IP : Transmission not working after string operations

I'm trying to simulate a simple TCP connection between a client and a server, on the localhost. Things are working well without line 22 on "client.c" file, where I'm doing a string operation. With that line un-commented, the server apparently does not make the connection with the client.
I've been searching around for quite long, but I found nothing strictly related to this. It'd be great if I got some help. :)
Files:
client.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <unistd.h>
#define BUFLEN 256
void error(char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, n;
//char filename[] = "file.txt"; // !!THE PROBLEM IS HERE!!
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[BUFLEN];
if (argc < 3) {
fprintf(stderr,"Usage %s server_address server_port\n", argv[0]);
exit(0);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(atoi(argv[2]));
inet_aton(argv[1], &serv_addr.sin_addr);
if (connect(sockfd,(struct sockaddr*) &serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
while(1) {
memset(buffer, 0 , BUFLEN);
fgets(buffer, BUFLEN-1, stdin);
n = send(sockfd,buffer,strlen(buffer), 0);
if (n < 0)
error("ERROR writing to socket");
}
return 0;
}
server.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#define MAX_CLIENTS 5
#define BUFLEN 256
void error(char *msg)
{
perror(msg);
exit(1);
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen;
char buffer[BUFLEN];
struct sockaddr_in serv_addr, cli_addr;
int n, i, j;
fd_set read_fds;
fd_set tmp_fds;
int fdmax;
if (argc < 2) {
fprintf(stderr,"Usage : %s port\n", argv[0]);
exit(1);
}
FD_ZERO(&read_fds);
FD_ZERO(&tmp_fds);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
portno = atoi(argv[1]);
memset((char *) &serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(struct sockaddr)) < 0)
error("ERROR on binding");
listen(sockfd, MAX_CLIENTS);
FD_SET(sockfd, &read_fds);
fdmax = sockfd;
// main loop
while (1) {
tmp_fds = read_fds;
if (select(fdmax + 1, &tmp_fds, NULL, NULL, NULL) == -1)
error("ERROR in select");
for(i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &tmp_fds)) {
if (i == sockfd) {
clilen = sizeof(cli_addr);
if ((newsockfd = accept(sockfd, (struct sockaddr *)&cli_addr, &clilen)) == -1) {
error("ERROR in accept");
}
else {
FD_SET(newsockfd, &read_fds);
if (newsockfd > fdmax) {
fdmax = newsockfd;
}
}
printf("New connection from IP %s, port %d, socket_client %d\n ", inet_ntoa(cli_addr.sin_addr), ntohs(cli_addr.sin_port), newsockfd);
}
else {
memset(buffer, 0, BUFLEN);
if ((n = recv(i, buffer, sizeof(buffer), 0)) <= 0) {
if (n == 0) {
printf("selectserver: socket %d hung up\n", i);
} else {
error("ERROR in recv");
}
close(i);
FD_CLR(i, &read_fds);
}
else { //recv > 0
printf ("I received from the client with socket %d, this message: %s\n", i, buffer);
}
}
}
}
}
close(sockfd);
return 0;
}
Compiling:
gcc client.c -o client
gcc server.c -o server
Running (in different terminals):
./server 9999
./client localhost 9999

Issue using c sockets with threads to read from and write to the socket

I want to write a TCP server-client chat, but when I start the two threads for reading from and writing to a socket at both sides, I think they block each other out. Can anyone help me with this?
Server Code:
/* A simple server in the internet domain using TCP the port number is passed as an argument */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <pthread.h>
struct server_args_runner{
char buffer [256];
int newsockfd;
pthread_t tid;
pthread_attr_t attr;
//read/write attribute (read == 0 and write == 1)
int rw;
};
void error(char *msg){
perror(msg);
exit(1);
}
void* server_runner_fun(void* args){
// this is the chat part!
// get args:
int n;
struct server_args_runner *sar = (struct server_args_runner*) args;
if(sar->rw == 0){
printf("server thread trys to read from socket...\n");
//read-part
while(1){
bzero(sar->buffer, 256);
n = read(sar->newsockfd, sar->buffer, 255);
if (n < 0){
error("ERROR reading from socket");
}
}
printf("%s\n", sar->buffer);
} else {
printf("server thread trys to write to socket...\n");
//write-part
while(1){
bzero(sar->buffer, 256);
fgets(sar->buffer, 255, stdin);
n = write(sar->newsockfd, sar->buffer, strlen((char *) &(sar->buffer)));
if (n < 0){
error("ERROR writing to socket");
}
}
}
}
int main(int argc, char *argv[]){
//fd = filedescriptor
int sockfd, portno, clilen;
struct sockaddr_in serv_addr, cli_addr;
int n;
if (argc < 2){
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
//socket(...) returns a descriptor
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1){
error("ERROR opening socket");
}
printf("Socket created successfully.\n");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = INADDR_ANY;
//htons(..) converts the short from hostbyteorder to networkbyteorder
serv_addr.sin_port = htons(portno);
if (bind(sockfd, (struct sockaddr *) &serv_addr,sizeof(serv_addr)) == -1){
error("ERROR on binding");
}
printf("binding successfull on port %d\n", portno);
listen(sockfd, 2);
clilen = sizeof(cli_addr);
printf("server is listening ...\n");
struct server_args_runner server_write_t, server_read_t;
server_write_t.newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen);
printf("server accepted connection to client.\n");
if (server_write_t.newsockfd < 0){
error("ERROR on accept");
}
//initializing both server_threads
pthread_attr_init(&server_write_t.attr);
pthread_attr_init(&server_read_t.attr);
server_write_t.rw = 1;
server_read_t.rw = 0;
bcopy(&server_write_t.newsockfd, &server_read_t.newsockfd, sizeof(server_write_t.newsockfd));
pthread_create(&server_write_t.tid, &server_write_t.attr, server_runner_fun, &server_write_t);
pthread_create(&server_read_t.tid, &server_read_t.attr, server_runner_fun, &server_read_t);
pthread_join(server_write_t.tid, NULL);
pthread_join(server_read_t.tid, NULL);
return 0;
}
Client code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>
struct client_args_runner{
char buffer [256];
int sockfd;
pthread_t tid;
pthread_attr_t attr;
//read/write attribute (read == 0 and write == 1)
int rw;
};
void error(char *msg){
perror(msg);
exit(0);
}
void* client_runner_fun(void* args){
// this is the chat part!
// get args:
int n;
struct client_args_runner *car = (struct client_args_runner*) args;
if(car->rw == 0){
printf("client thread trys to read from socket...\n");
//read-part
while(1){
bzero(car->buffer, 256);
n = read(car->sockfd, car->buffer, 255);
if (n < 0){
error("ERROR reading from socket");
}
}
printf("%s\n", car->buffer);
} else {
printf("client thread trys to write to socket...\n");
//write-part
while(1){
bzero(car->buffer, 256);
fgets(car->buffer, 255, stdin);
n = write(car->sockfd, car->buffer, strlen((char *) &(car->buffer)));
if (n < 0){
error("ERROR writing to socket");
}
}
}
}
int main(int argc, char *argv[]){
int portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
if (argc < 3){
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
struct client_args_runner client_write_t, client_read_t;
client_write_t.sockfd = socket(AF_INET, SOCK_STREAM, 0);
bcopy(&client_write_t.sockfd, &client_read_t.sockfd,
sizeof(client_write_t.sockfd));
if (client_write_t.sockfd == -1){
error("ERROR on creating socket_file_descriptor");
}
printf("socket created successfully.\n");
server = gethostbyname(argv[1]);
printf("hostname is valid.\n");
if(server == NULL){
fprintf(stderr, "Error, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *) server->h_addr, (char *) &serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
printf("before connecting to client..\n");
if (connect(client_write_t.sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) == -1){
error("ERROR connecting");
}
printf("client connected successfully to server.\n");
//initializing both client_threads
pthread_attr_init(&client_write_t.attr);
pthread_attr_init(&client_read_t.attr);
client_write_t.rw = 1;
client_read_t.rw = 0;
pthread_create(&client_write_t.tid, &client_write_t.attr, client_runner_fun, &client_write_t);
pthread_create(&client_read_t.tid, &client_read_t.attr, client_runner_fun, &client_read_t);
pthread_join(client_write_t.tid, NULL);
pthread_join(client_read_t.tid, NULL);
return 0;
}
Your printfs in both the client and server readers are outside the while(1) loops, so your client and server are communicating fine, you just aren't printing anything you read from the sockets.

Killing forked process in a socket server

I've written a socket based multi client server and a client as an assigment, but I don't seem to be able to get rid of forked processes. Every time I close the client, or enter the exiting command, the process doesn't seem to close. When checked ps aux| grep server there is a defuct process. How can I get rid of them, what am I doing wrong when closing forked prosses.
The server:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
void doprocessing (int sock)
{
int n;
char buffer[5];
time_t rawtime;
char tim[22];
char dat[20];
char day[16];
char yer[18];
while(1)
{
bzero(buffer,5);
n = read(sock,buffer,5);
if (n < 0) error("ERROR reading from socket");
printf("Got %.3s command.\n",buffer);
if (strcasecmp(buffer, "tim\n") == 0)
{
rawtime = time(NULL);
strncpy(tim, "Current time: ", 14);
strncpy(tim+14, (ctime(&rawtime))+11, 8);
n = write(sock, tim, 22);
}
else if (strcasecmp(buffer, "dat\n") == 0)
{
rawtime = time(NULL);
strncpy(dat, "Current date: ", 14);
strncpy(dat+14, (ctime(&rawtime))+4, 6);
n = write(sock, dat, 20);
}
else if (strcasecmp(buffer, "day\n") == 0)
{
rawtime = time(NULL);
strncpy(day, "Current day: ", 13);
strncpy(day+13, (ctime(&rawtime)), 3);
n = write(sock, day, 16);
}
else if (strcasecmp(buffer, "yer\n") == 0)
{
rawtime = time(NULL);
strncpy(yer, "Current year: ", 14);
strncpy(yer+14, (ctime(&rawtime))+20, 4);
n = write(sock, yer, 18);
}
else if (strcasecmp(buffer, "com\n") == 0)
{
n = write(sock, "TIM - current time\nDAT - Month and day\nDAY - current weekday\nYER - Year\nEXT - exit", 82);
}
else if (strcasecmp(buffer, "ext\n") == 0)
{
n = write(sock, "Exiting", 7);
break;
}
else n = write(sock, "Wrong command enter COM to see commands.",40);
if (n < 0) error("ERROR writing to socket");}
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen, n;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int pid;
if (argc < 2)
{
fprintf(stderr, "ERROR, no port provided");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding");
listen(sockfd, 5);
clilen = sizeof(cli_addr);
while(1)
{
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) error("ERROR on accept");
pid = fork();
if (pid < 0) error("ERROR on fork");
if (pid == 0)
{
close(sockfd);
doprocessing(newsockfd);
exit(-1);
}
else close(newsockfd);
}
close(sockfd);
return 0;
}
The Client:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char rbuffer[256];
char sbuffer[256];
if (argc < 3)
{
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting");
while(1)
{
printf("Enter a command: ");
bzero(sbuffer,sizeof(sbuffer));
fgets(sbuffer,255,stdin);
n = write(sockfd,sbuffer,5);
if (n < 0) error("ERROR writing to socket");
bzero(rbuffer,sizeof(rbuffer));
n = read(sockfd,rbuffer,255);
if (n < 0) error("ERROR reading from socket");
printf("%s\n",rbuffer);
if (strcasecmp(sbuffer, "ext\n") == 0) break;
}
close(sockfd);
return 0;
}
A process is going to be visible in ps output as 'defunct' (sometimes called zombie process) until it's exit status is going to be collected with wait() or waitpid().
There are following ways of getting rid of those zombie processes:
Wait for child completion using wait() or waitpid() in parent process. Obviously, it's hard to do anything else in the parent this way.
Create a separate thread immediately after spawning a child and waitpid inside this thread.
In your parent, install a handler for SIGCHLD signal and waitpid() inside this handler.
If your system allows that, set to ignore SIGCHLD signal.

Multi client socket server client disconnects after first request to the server. (C programming)

I am trying to write a multi-client socket server and a client to go with that server, which would send server simple requests, like, current time, date etc. My problem seems to be, that I can't get the client stay connected, because after first request it seems to disconnect and request doesn't reach the server.
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <time.h>
void error(char *msg)
{
perror(msg);
exit(1);
}
void doprocessing (int sock)
{
int n;
char buffer[5];
bzero(buffer,5);
n = read(sock,buffer,4);
time_t rawtime;
char tim[22];
char dat[20];
char day[16];
char yer[18];
if (n < 0) error("ERROR reading from socket");
printf("Got %.3s command.\n",buffer);
if (strcasecmp(buffer, "tim\n") == 0)
{
rawtime = time(NULL);
strncpy(tim, "Current time: ", 14);
strncpy(tim+14, (ctime(&rawtime))+11, 8);
n = write(sock, tim, 22);
}
else if (strcasecmp(buffer, "dat\n") == 0)
{
rawtime = time(NULL);
strncpy(dat, "Current date: ", 14);
strncpy(dat+14, (ctime(&rawtime))+4, 6);
n = write(sock, dat, 20);
}
else if (strcasecmp(buffer, "day\n") == 0)
{
rawtime = time(NULL);
strncpy(day, "Current day: ", 13);
strncpy(day+13, (ctime(&rawtime)), 3);
n = write(sock, day, 16);
}
else if (strcasecmp(buffer, "yer\n") == 0)
{
rawtime = time(NULL);
strncpy(yer, "Current year: ", 14);
strncpy(yer+14, (ctime(&rawtime))+20, 4);
n = write(sock, yer, 18);
}
else if (strcasecmp(buffer, "com\n") == 0)
{
n = write(sock, "TIM - current time\nDAT - Month and day\nDAY - current weekday\nYER - Year", 71);
}
else n = write(sock, "Wrong command enter COM to see commands.",40);
if (n < 0) error("ERROR writing to socket");
}
int main(int argc, char *argv[])
{
int sockfd, newsockfd, portno, clilen, n;
char buffer[256];
struct sockaddr_in serv_addr, cli_addr;
int pid;
if (argc < 2)
{
fprintf(stderr, "ERROR, no port provided");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(portno);
serv_addr.sin_addr.s_addr = INADDR_ANY;
if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding");
listen(sockfd, 5);
clilen = sizeof(cli_addr);
while(1)
{
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0) error("ERROR on accept");
pid = fork();
if (pid < 0) error("ERROR on fork");
if (pid == 0)
{
close(sockfd);
doprocessing(newsockfd);
exit(0);
}
else close(newsockfd);
}
}
Thats the server, and the client:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
void error(const char *msg)
{
perror(msg);
exit(0);
}
int main(int argc, char *argv[])
{
int sockfd, portno, n;
struct sockaddr_in serv_addr;
struct hostent *server;
char rbuffer[256];
char sbuffer[256];
if (argc < 3)
{
fprintf(stderr,"usage %s hostname port\n", argv[0]);
exit(0);
}
portno = atoi(argv[2]);
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) error("ERROR opening socket");
server = gethostbyname(argv[1]);
if (server == NULL)
{
fprintf(stderr,"ERROR, no such host\n");
exit(0);
}
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
serv_addr.sin_port = htons(portno);
if (connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting");
for(;;)
{
printf("Enter a command: ");
bzero(sbuffer,sizeof(sbuffer));
fgets(sbuffer,255,stdin);
n = write(sockfd,sbuffer,strlen(sbuffer));
if (n < 0) error("ERROR writing to socket");
bzero(rbuffer,sizeof(rbuffer));
n = read(sockfd,rbuffer,255);
if (n < 0) error("ERROR reading from socket");
printf("%s\n",rbuffer);
}
close(sockfd);
return 0;
}

Resources