PaeneInsula
PaeneInsula

Reputation: 2100

In C, append to file open for read by another program on Windows console and Linux

I have two different C programs running on the same machine. The first program, called FileReader, opens a file for reading, and keeps it open. Periodically, I want another program, FileAppender, to open the file using the "a" (append) mode, append data, and then close the file.

But I don't want FileReader to close the file whenever the FileAppender needs to append data.

My questions: First, can this be done at all, and if so, can it be done in a portable, reliable way for both Windows console program and Linux? The reason I'm asking about "reliable" is because I am afraid that in testing it may work, but not necessarily reliably.

Second, if this can be done, portability- and reliability-wise, how can the FileReader program know if data has been appended? One thought I had was to do an fseek to EOF, but worry about the situation where FileAppender is still in the process of writing data to the file.

Upvotes: 1

Views: 247

Answers (1)

ryyker
ryyker

Reputation: 23218

The Linux/UNIX -tail command as described in the comments does not exist for windows, But yes, there are several ways to do this even without that command. Here is one that I have used, that should work cross-platform:

First recognize you are describing a shared (file system) resource, that can only be accessed by one process at any one time. The two (or more) applications need some kind of semaphore (signalling) method to signal the current state of the target file by checking the existence of another. I have used a Token file for this, and it has worked for me. A Token file is simply a file with a unique name that indicates permission to access the target file, where target file is the file being edited by more than one process. This Token file can be checked by processes (applications) for its existence. If token exists, the target file is busy, and should not be accessed. If the token does not exist, create it, then access the target file. Close token when done appending to target.

Simple concept flow:

Process 1
while(token exists)
{
   //Sleep(20)
}
create token
Open target file for append
write to target file
close target file
close token

Process 2
while(token exists)
{
   //Sleep(20)
}
create token
Open target file for append
write to target file
close target file
close token

Upvotes: 1

Related Questions