I made a program that listen on a specific ipv6 address and a port, which displays what it receives. My program works perfectly; I haven't tested everything yet, but the basic usage works.
I need your advice for this problem: what is the best way to continuously listen?
When I launch the program, I want to stop listening by stopping it with Ctrl+C
in the shell. But If I do that, some important code may not be executed. Here is what I have at the end of my main function:
while(1){
// reception de la chaine de caracteres
if(recvfrom(sockfd, buf, 1024, 0
, (struct sockaddr *) &client, &addrlen) == -1)
{
perror("recvfrom");
close(sockfd);
exit(EXIT_FAILURE);
}
buf[1023] = '\0';
// print the received char
printf("%s", buf);
}
// close the socket
close(sockfd);
return 0;
First, I think that this is passive waiting since the function recvfrom
stop the program until it receives something. So using a while is not a problem. The problem is, that close(sockfd)
may not be executed.
So I am looking for a simple way to execute some code when the program is stopped. I thought of threads but this may be too complex for this problem.