V
V
Vi Vola2020-02-19 08:58:02
C++ / C#
Vi Vola, 2020-02-19 08:58:02

How to correctly release resources in an ever-running application?

What is the correct way to release resources in an application that should run from the moment the device is started until it is turned off? In my case, the application is a certain driver. On the one hand, you don’t have to release - when you close the application, the files will be closed, and all streams will be killed by the operating system, on the other hand, it’s still wrong to do this, because I feel that I potentially loaded a gun and pointed it at my leg.

void* first_thread (void* arg)
{
  int fd = open("/path/to/file", O_RDWR);
  // ...
  while (true) {
    // work with file
  }
}

void* second_thread (void* arg)
{
  int fd = open("/path/to/second_file", O_RDWR);
  // ...
  while (true) {
    // work with file
  }
}

int main(int argc, char *argv[])
{
  pthread_create(NULL, NULL, first_thread, NULL);
  pthread_create(NULL, NULL, second_thread, NULL);

  return foo(argc, argv); // тут что то продолжаем делать и приложение при этом не завершается
}


At what point should files be closed and streams terminated?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Gornostaev, 2020-02-19
@hakain

Before the program is terminated, it is necessary to send some kind of termination signal to the threads, which they will check at each iteration of the loop and terminate it if necessary, and close the files after the loop.

V
Vladimir Korotenko, 2020-02-19
@firedragon

In POSIX systems, the OS must send a signal before nailing
https://ru.wikipedia.org/wiki/SIGTERM
Windows has a similar mechanism
Judging by the STM32 tag, do you have some kind of OS installed? See the documentation for the implementation of TASK MANAGER and SIGTERM if implemented, then insert a handler and close files in it

M
mayton2019, 2020-02-19
@mayton2019

Since we are talking about the "C" language, it is necessary to correctly handle open / read / write / fseek / close errors and respond to them. And close file handles for any possible outcome. Well, don't forget to do free() after malloc(). Roughly speaking, the number of mallocs should always be equal to free.
If there was a death of the posix thread, then you need to somehow find all the abandoned orphan descriptors and close them too. That is, the parent process must somehow see them.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question