Thread stucks in the infinite loop when executed - c

I have developed a chat server program using threads. In this program there are two threads:
One to receive data
One to send data
Both of the threads contain the infinite loop in order to continuously send and receive data. But when it is executed the thread for receiving data gets stuck in the loop.
The code of the server:
{
addr_len=sizeof(cli_addr);
cli_sock=accept(sock,(struct sockaddr *)&cli_addr,&addr_len);
if(cli_sock<0)
printf("\nConnetion Error\n");
else
printf("conneted\n");
status_s=pthread_create(&thread_s,NULL,send_data,&cli_sock);
if(status_s==0)
printf("sending");
status_r=pthread_create(&thread_r,NULL,recieve_data,&cli_sock);
if(status_r==0)
printf("recieving");
}
}
void *recieve_data(void *num)
{
int *sock_r=(int *) num;
int sock=*sock_r;
char msg[50];
while(1)
{
recv(sock_r,msg,sizeof(msg),0);
if(strcmp(msg,"exit")==0)
{
break;
}
printf("recieved data:");
recv(sock_r,msg,sizeof(msg),0);
printf("\n%s",msg);
}
}
void *send_data(void *num)
{
int *sock_s=(int *) num;
int sock=*sock_s;
char msg[50];
while(1)
{
gets(msg);
//printf("sending data");
if(strcmp(msg,"exit")==0)
{
break;
}
send(sock_s,msg,sizeof(msg),0);
}
send(sock,msg,sizeof(msg),0);
}

Would be better if control commands like "exit" are int based.
Also, receive data doesn't handle peer connection closure status. Ex:
Copied from here.
// Receive until the peer closes the connection
do {
iResult = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if ( iResult > 0 )
printf("Bytes received: %d\n", iResult);
else if ( iResult == 0 )
printf("Connection closed\n");
else
printf("recv failed: %d\n", WSAGetLastError());
} while( iResult > 0 );

Related

design a Unix message queue server for multiple clients

What should I modify in the below codes in order to use only one message queue for one server and
multiple clients. I'm pretty sure I need to assign different values to msgid and then use that to fetch the messages from the message queue but not completely sure if I'm right and how to implement it. I would be grateful for any help.
Code1:
struct my_msg_st {
long int my_msg_type;
char some_text[BUFSIZ];
};
int main() {
int running = 1;
int msgid;
struct my_msg_st some_data;
long int msg_to_receive = 0
msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
if (msgid == -1) {
fprintf(stderr, “msgget failed with error: %d\n”, errno);
exit(EXIT_FAILURE);
}
while(running) {
if (msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_receive, 0) == -1) {
fprintf(stderr, “msgrcv failed with error: %d\n”, errno);
exit(EXIT_FAILURE);
}
printf(“You wrote: %s”, some_data.some_text);
if (strncmp(some_data.some_text, “end”, 3) == 0) {
running = 0;
}
}
if (msgctl(msgid, IPC_RMID, 0) == -1) {
fprintf(stderr, “msgctl(IPC_RMID) failed\n”);
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
Code 2:
#define MAX_TEXT 512
struct my_msg_st {
long int my_msg_type; char some_text[MAX_TEXT];
};
int main() {
int running = 1;
struct my_msg_st some_data; int msgid;
char buffer[BUFSIZ];
msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
if (msgid == -1) {
fprintf(stderr, “msgget failed with error: %d\n”, errno);
exit(EXIT_FAILURE);
}
while(running) {
printf(“Enter some text: “);
fgets(buffer, BUFSIZ, stdin);
some_data.my_msg_type = 1;
strcpy(some_data.some_text, buffer);
if (msgsnd(msgid, (void *)&some_data, MAX_TEXT, 0) == -1) {
fprintf(stderr, “msgsnd failed\n”);
exit(EXIT_FAILURE);
}
if (strncmp(buffer, “end”, 3) == 0) {
running = 0;
}
}
exit(EXIT_SUCCESS);
}
I suggest that you create a single queue and each message that you push to the queue should have a different value for my_msg_type instead of hard coding it to 1 as you have done. This is the mapping between the client and server. Each client can be numbered from 1 till n.
some_data.my_msg_type = client_id;
Once this is done in each client you can call msgrcv with its corresponding client ID. This can be done by using the client ID as the 4th argument in msgrcv.
msgrcv(msgid, (void *)&some_data, BUFSIZ, msg_to_receive, client_id)
This way you have a single server generating data for multiple clients.
Hope that helps!

How to reconnect to TCP server after network goes down and comes back up again?

I have a raspberry pi that connects to a TCP server and sends some data every couple of seconds, I want to be able to handle all kind of failures and disconnects, so at the moment I am trying a test where I disconnect the Huawei USB dongle that I am connecting through.
I have a thread that runs in the background and check the connection periodically. The code does not reconnect when I remove the USB dongle and plug it back in sometime later, I need help on how to make this more robust. At the moment on the server side I see that after I plug back in the USB dongle I see the client connect but immediately disconnect from it.
The thread is called KeepSocketOpen and inside here I call a ping function to 8.8.8.8 to see if the connection is still active and here is my code, I'm kind of new to socket programming so excuse the mess:
int ping(char *ipaddr)
{
char *command = NULL;
FILE *fp;
int x, match=0;
char* result = NULL;
size_t len = 0;
asprintf (&command, "%s %s -p 50 -r 3", "fping", ipaddr);
//printf ("%s %s -q 2>&1", "fping", ipaddr);
fp = popen(command, "r");
if (fp == NULL) {
fprintf(stderr, "Failed to execute fping command\n");
free(command);
return -1;
}
while(getline(&result, &len, fp) != -1) {
fputs(result, stdout);
//printf("%s",result);
}
for(x=0;x<len;x++)
{
if(x>5 && result[x]=='e'&& result[x-1]=='v'&& result[x-2]=='i'&& result[x-3]=='l'&& result[x-4]=='a')
{
match=1;
break;
}
}
if(match==0)
sleep(5);
free(result);
fflush(fp);
if (pclose(fp) != 0) {
perror("Cannot close stream.\n");
}
free(command);
//printf("%s\r\n",result);
if(match==0)
return -1;
else
return 1;
}
void* KeepSocketOpen(void *arg)
{
pthread_t id= pthread_self();
char tcprxbuff[1024];
int numbytes, status=0,attempts,reuse=1;
struct timeval timeout={0};
timeout.tv_sec=10;
timeout.tv_usec=0;
printf("in sock thread\r\n");
while(1)
{
if(is_socket_connected==0)
{
sock=socket(AF_INET,SOCK_STREAM,0);
addr.sin_family = AF_INET;
addr.sin_port = htons(34879);
addr.sin_addr.s_addr=inet_addr("X.X.X.X");
attempts=0;
setsockopt(sock,SOL_SOCKET,SO_SNDTIMEO,(char *)&timeout,sizeof(timeout));
setsockopt(sock,SOL_SOCKET,SO_RCVTIMEO,(char *)&timeout,sizeof(timeout));
setsockopt(sock, SOL_SOCKET,SO_REUSEADDR,&reuse,sizeof(reuse));
status=connect(sock, (struct sockaddr *) &addr,sizeof (addr));
// wait for 5s and see if the socket has connected
do
{
delay(5);
}
while(errno && attempts++<1000);
if (attempts >=1000 || errno) // this is the fail case
{
printf("socket not connected %s\r\n",strerror(errno));
is_socket_connected=0;
close(sock);
//shutdown(sock,SHUT_RDWR);
sleep(30);
}
else
{
// fcntl(sock, F_SETFL, O_NONBLOCK);
printf("socket reconnected %d,%s\r\n",attempts,strerror(errno));
is_socket_connected=1;
write(sock, "HI FROM RASPI", strlen("HI FROM RASPI"));
}
}
else
{
numbytes=read(sock,tcprxbuff,sizeof(tcprxbuff));
if(numbytes==0)// if this is zero, socket was closed by server
{
is_socket_connected=0;
while(close(sock)==-1);
}
else
{
printf("socket connected:%d\r\n",numbytes);
status = ping("8.8.8.8");
if (status!=-1) {
printf("socket still connected:%d\r\n",status);
is_socket_connected=1;
} else {
printf("socket disconnected:%d\r\n",status);
is_socket_connected=0;
//shutdown(sock,SHUT_RDWR);
while(close(sock)==-1);
}
}
sleep(30);
}
}
}

UNIX Domain socket programming in C, printing issue

I am having a printing issue with my server. I want there to be simultaneous printing when I have 2 or more clients active on terminals. However, I am only printing from one client at a time. Once I close a client, the other clients are free to write to the server. What can I do to fix my problem?
I have tried to fork the printing section, which I think didn't really do anything. (Just realized if I do this, then the select system call is a waste, i'd rather use the select system call) *edit
while(TRUE) {
FD_ZERO(&readfds);
FD_SET(socket1, &readfds);
FD_SET(socket2, &readfds);
FD_SET(socket3, &readfds);
select(socket3+1, &readfds, NULL, NULL, NULL);
//add socket1
if(FD_ISSET(socket1, &readfds)) {
if((client_socket1 = accept(socket1, NULL, NULL)) < 0) {
perror("accept1");
exit(EXIT_FAILURE);
}
printf("New Connection\n");
puts("Welcome message1 sent successfully\n");
}
//add socket2
if(FD_ISSET(socket2, &readfds)) {
if((client_socket2 = accept(socket2, (struct sockaddr *)&addr2, (socklen_t*)&addr2)) < 0) {
perror("accept2");
exit(EXIT_FAILURE);
}
printf("New Connection\n");
puts("Welcome message2 sent successfully\n");
}
//add socket 3
if(FD_ISSET(socket3, &readfds)) {
if((client_socket3 = accept(socket3, (struct sockaddr *)&addr3, (socklen_t*)&addr3)) < 0) {
perror("accept3");
exit(EXIT_FAILURE);
}
printf("New Connection\n");
puts("Welcome message3 sent successfully\n");
}
//print from socket 3
while( (ready = read(client_socket3, buffer, sizeof(buffer))) > 0) {
printf("%s\n", buffer);
}
//print from socket 2
while( (ready = read(client_socket2, buffer, sizeof(buffer))) > 0) {
printf("%s\n", buffer);
}
//print from socket 1
while( (ready = read(client_socket1, buffer, sizeof(buffer))) > 0) {
printf("%s\n", buffer);
}
}
You need to add your client sockets to the fd_set and select statement before attempting to read from them. Also, you should make all your sockets non-blocking. Otherwise, the read call will block until you get data.
Here's a quick fix that uses recv instead of read to read the sockets, but with the async flag of MSG_DONTWAIT.
I didn't see anywhere where you were closing your client sockets or handling errors properly. So I inserted some code as a hint. Also, it's never a good idea to "printf" a buffer of data from a socket directly. Because you never know if the data you received is null terminated. Always null terminate your buffer after you read the data off the socket.
Change this block of code:
//print from socket 3
while( (ready = read(client_socket3, buffer, sizeof(buffer))) > 0) {
printf("%s\n", buffer);
}
To this:
while (1)
{
int result;
result = recv(client_socket3, buffer, sizeof(buffer)-1, MSG_DONTWAIT);
if ((result == -1) &&
((errno == EAGAIN) || (errno==EWOULDBLOCK)) )
{
// no more data available, but could be available later
// use the socket with "select" above to wait for more data
}
else if ((result == -1) || (result == 0))
{
// remote close or unrecoverable error
close(client_socket3);
client_socket3=-1;
}
else
{
// null terminate the buffer before printing
buffer[result] = '\0';
printf("%s\n", buffer);
}
}

how to run the timer task in parallel with socket receive data?

void main()
{
HANDLE h1,h2,h3;
uint8 data;
double Task2ms_Raster, Task10ms_Raster, Task100ms_Raster ;
CreateSocket();
XCP_FN_TYPE Xcp_Initialize( );
while(1)
{
data = recv(fd, recv_data, 99, 0);
if (data == SOCKET_ERROR) {
printf("recv failed with error %d\n", WSAGetLastError());
}
else
{
pChunkData = &recv_data;
chunkLen = sizeof(pChunkData);
XcpIp_RxCallback ((uint16) chunkLen, (char*) pChunkData, (uint16) port);
}
}
h1=TimerTask(2,TASK1,&Task2ms_Raster);
h2=TimerTask(10,TASK2,&Task10ms_Raster);
h3=TimerTask(100,TASK3,&Task100ms_Raster);
XCP_FN_TYPE XcpIp_OnTcpCxnClosed( port );
}
I have created the server socket and recieving data from the client via the ip address and the port number. I have to run the timer task in parallel with the recieve data from the socket.The function definition of create scoket and TimerTask functionality is not shown. So could anyone please help me how to run the timer task parallel to it ??

socket programming with select

I have two nodes communicating with a socket. Each node has a read thread and a write thread to communicate with the other. Given below is the code for the read thread. The communication works fine between the two nodes with that code. But I am trying to add a select function in this thread and that is giving me problems (the code for select is in the comments. I just uncomment it to add the functionality). The problem is one node does not receive messages and only does the timeout. The other node gets the messages from the other node but never timesout. That problem is not there (both nodes send and receive messages) without the select (keeping the comments /* */).
Can anyone point out what the problem might be? Thanks.
void *Read_Thread(void *arg_passed)
{
int numbytes;
unsigned char *buf;
buf = (unsigned char *)malloc(MAXDATASIZE);
/*
fd_set master;
int fdmax;
FD_ZERO(&master);
*/
struct RWThread_args_template *my_args = (struct RWThread_args_template *)arg_passed;
/*
FD_SET(my_args->new_fd, &master);
struct timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
int s_rv = 0;
fdmax = my_args->new_fd;
*/
while(1)
{
/*
s_rv = -1;
if((s_rv = select(fdmax+1, &master, NULL, NULL, &tv)) == -1)
{
perror("select");
exit(1);
}
if(s_rv == 0)
{
printf("Read: Timed out\n");
continue;
}
else
{
printf("Read: Received msg\n");
}
*/
if( (numbytes = recv(my_args->new_fd, buf, MAXDATASIZE-1, 0)) == -1 )
{
perror("recv");
exit(1);
}
buf[numbytes] = '\0';
printf("Read: received '%s'\n", buf);
}
pthread_exit(NULL);
}
You must set up master and tv before each call to select(), within the loop. They are both modified by the select() call.
In particular, if select() returned 0, then master will now be empty.

Resources