2

When the JVM creates a log file with log rotation enabled, it creates a file with a name like this:

logfile.0.current

After it reaches a file size threshold, and rotates to a new file, it moves the file to logfile.0 and creates a new file: logfile.1.current

I have a program which reads from these logfiles and does some processing on it and then writes the content to a single file.

The code for reading from the file is something similar to this:

ssize_t numRead = read(_fd, buffer, BUF_SIZE - 1);
// I want to know how to handle the situation if file gets deleted here

char * msg = new char[numRead + 1];
strncpy(msg, buffer, numRead);
msg[numRead] = '\0';
// write the msg to a different file.

But I'm struggling to handle the situation where logfile.0.current gets moved to logfile.0.

  • What happens to the file descriptor at that point?
  • Is there any signal that I can detect at this point to handle it?
BlueChips23
  • 1,861
  • 5
  • 34
  • 53
  • First, make your life simpler by using std::string, not C-style arrays of char. –  Jul 12 '18 at 21:02
  • To clarify, are you using C or C++? And, is an OS/platform-dependent solution viable or no? – Arthur Dent Jul 12 '18 at 21:12
  • @ArthurDent It's C++. And it's running on RedHat Linux, if it helps. – BlueChips23 Jul 12 '18 at 21:49
  • 1
    @BlueChips23 then the goal is to get and maintain a handle and lock the file (I recommend [the fcntl API](https://www.manpagez.com/man/2/fcntl/) for Linux). See also [this example](https://gavv.github.io/blog/file-locks/#posix-record-locks-fcntl) – Arthur Dent Jul 12 '18 at 22:05
  • @ArthurDent If I understand correctly, the idea is to open the file and lock the file with fcntl. This way JVM won't be able to delete it. Is that right? But couple questions: 1) Will JVM be still able to write to it? 2) Is there any reason why fcntl is preferred over flock()? – BlueChips23 Jul 13 '18 at 13:26
  • 1
    I read a little more about fcntl vs flock. Seems like fcntl is standardized and is supported on more Unix systems. – BlueChips23 Jul 13 '18 at 13:47
  • If you have no control over the Java code, this is much harder problem. Ideal solution is to create lockfile and both agree to check it. – Arthur Dent Jul 17 '18 at 19:49

0 Answers0