I have a problem with terminating sections in a C program. After catching a SIGINT
signal in one thread I wanted to exit all threads and I don't really know how because I have infinite loops in these loops. The program waits for input from server or stdin. So I used signal handler.
I don't really know if I am doing this right way and I don't really understand how cancel in OpenMP works. I didn't find a proper tutorial or lecture for this.
My task is after catching SIGINT
signal, terminate the program. But when I use exit()
in the handler it leaves un-freed memory obviously. I will be glad for any advise, thank you.
#pragma omp parallel num_threads(2)
{
#pragma omp sections
{
#pragma omp section
{
void intHandler(int dummy)
{
char * welcome1 = calloc(strlen(username)+14,sizeof(char));
strcat(welcome1,username);
strcat(welcome1," logged out\r\n");
if(send(client_socket,welcome1,strlen(welcome1),0) < 0)
{
callError("ERROR: cannot send socked");
}
free(welcome1);
#pragma omp cancel section
}
signal(SIGINT, intHandler);
int i = 0, j = 1;
while(1)
{
str = (char*)malloc(sizeof(char));
while((c = getc(stdin)) != '\n')
{
str = (char*)realloc(str, j * sizeof(char));
str[i] = c;
i++;
j++;
}
str = (char*)realloc(str, j * sizeof(char));
str[i] = '\0';
if(strlen(str)!=0)
{
bufferIn = message(username,str);
if(send(client_socket,bufferIn,strlen(bufferIn),0) < 0)
{
callError("ERROR: cannot send socked");
}
free(bufferIn);
}
free(str); i = 0; j = 1;
}
#pragma omp cancellation point section
}
#pragma omp section
{
void intHandler(int dummy)
{
char * welcome1 = calloc(strlen(username)+14,sizeof(char));
strcat(welcome1,username);
strcat(welcome1," logged out\r\n");
if(send(client_socket,welcome1,strlen(welcome1),0) < 0)
{
callError("ERROR: cannot send socked");
}
free(welcome1);
#pragma omp cancel section
}
signal(SIGINT, intHandler);
char buffer[4096];
ssize_t length;
int received = 0;
int data_cap = 4096;
while(1)
{
data = calloc(BUFFER_LEN,sizeof(char));
while ((length = read(client_socket, buffer, BUFFER_LEN-1)) > 0)
{
received += length;
buffer[length] = '\0';
if (received > data_cap)
{
data = realloc(data,sizeof(char) * data_cap * 2);
data_cap = data_cap * 2;
}
strcat(data, buffer);
if(!isEnough(data))
{
break;
}
}
printf("%s", data);
free(data); bzero(buffer,BUFFER_LEN); data_cap = 4096; received = 0; length = 0;
}
#pragma omp cancellation point section
}
}
}