Solved

Is it possibel to write and read to a file, same time by different applications?

Posted on 2011-03-01
6
1,133 Views
Last Modified: 2012-05-11
Hi,
Will this be possible?
"GUI application desiged in java reads from a file continuosly and low level code written in C  writes to the same file continuosly same time"?

If this read/write continuosly to a common file from single writer and  single reader is not possible, can anyone suggest how to have syncronization for Reading/writing?

GUI application and dll both are in same process, i dont know if there is anyway to use IPC mechanism to avoid Reader/Writer's problem between GUI developed in java and back end code developed in C.

PS:
1)C function which writes to the same file is a dll function, dll is loaded by GUI application itself.
2)GUI application designed in java using JNI to make C cals to dll.
0
Comment
Question by:srimallikarthik
6 Comments
 
LVL 15

Expert Comment

by:WalkaboutTigger
ID: 35014953
Why not have an arbitrator that actually writes to the file and the C application and the Java application send the arbitrator the data to write.

This seems the easiest route.  That way there are no possibilities of contention and the streams are synchronized in a first-in-first-out manner.
0
 
LVL 4

Accepted Solution

by:
parnasso earned 500 total points
ID: 35015106
I agree with WalkaboutTigger. Nevertheless, to answer your question strictly "Is it possibel to write and read to a file, same time by different applications?" Yes.

In Windows API when you create/open a file you pass a share mode parameter. In order to allow write and read operations for different processes this parameter is FILE_SHARE_READ | FILE_SHARE_WRITE. For instance, (in C code, i-m sorry about Java)
CreateFile(argv[1],               // file name 
                       GENERIC_READ,          // open for reading 
                        FILE_SHARE_READ | FILE_SHARE_WRITE,                     // share mode
                       NULL,                  // default security 
                       OPEN_EXISTING,         // existing file only 
                       FILE_ATTRIBUTE_NORMAL, // normal file 
                       NULL);                 // no template 

Open in new window


Find in the following link the full documentation of the CreateFile API call http://msdn.microsoft.com/en-us/library/aa363858%28v=vs.85%29.aspx

Hope this helps
0
 
LVL 30

Expert Comment

by:Zoppo
ID: 35015124
Hi srimallikarthik,

depending on your needs it might be worthwhile to take a look at file mapping: http://msdn.microsoft.com/en-us/library/aa366556%28v=vs.85%29.aspx

ZOPPO
0
Why spend so long doing email signature updates?

Do you spend loads of your time carrying out email signature updates? Not very interesting are they? Don’t let signature updates get you down. Let Exclaimer Cloud - Signatures for Office 365 make managing email signatures a breeze.

 

Author Comment

by:srimallikarthik
ID: 35015153
parnasso,

"same file is being shared between writer function (C) and reader function (JAVA)"

As per CreateFile  mode parameter, If i create a file in my C library code with these mode parameters and
let java application to read the same file. Will there be no issues?

"i will be continuosly writing in a thread to the file in C funtion and reading from the file is happening
in application java thread continously"
0
 
LVL 10

Expert Comment

by:gordon_vt02
ID: 35017403
I used a RandomAccessFile to create a tail emulator in Java.  This code should do what you need:

 
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.concurrent.CountDownLatch;

public class ContinuousFileReader implements Runnable {
    private final AtomicBoolean stopRequested = new AtomicBoolean(false);
    private final CountDownLatch stoppedLatch = new CountDownLatch(1);
    private RandomAccessFile randomFile;
    
    public ContinuousFileReader(File file) throws IOException {
        this.randomFile = new RandomAccessFile(file, "r");
    }
    
    public void stop() {
        stopRequested.compareAndSet(false, true);
    }
    
    public void waitForStop() throws InterruptedException {
        // blocks until stoppedLatch has been released
        stoppedLatch.await();
    }
	
    @Override
    public void run() {
        try {
            long filePointer = 0;
            while (!stopRequested.get()) {
                long fileLength = randomFile.length();
                if (fileLength > filePointer) {
                    randomFile.seek(filePointer);
                    for (String line = randomFile.readLine(); line != null; line = randomFile.readLine()) {
                        processLine(line);
                    }
                    filePointer = randomFile.length();
                }
                try {
                    Thread.sleep(POLLING_INTERVAL);
                } catch (InterruptedException ie) {
                    // handle interrupt -- options are to stop reading, which is implemented
                    // here, or ignore the interrupt and continue reading until another thread
                    // tells us to stop.
                    stop();
                    // set the interrupt status of this thread, ensuring the interrupt propagates
                    Thread.currentThread().interrupt();
                }
            }
        } catch (IOException ioe) {
            // log exception or otherwise handle to notify program
            // of read problem
        } finally {
            try {
                randomFile.close();
            } catch (IOException ioe) {
                // handle IO exception when file closes
            }
            // open latch to release threads blocked on waitForStop()
            stoppedLatch.countDown();
        }
    }
    
    private void processLine(String line) {
        // do something with the text
    }
}

Open in new window


Then, in your main you can start a background thread to read from the file:

public static void main(String[] args) {
    // assume args[0] is the filename
    File file = new File(args[0]);
    ContinuousFileReader reader;
    try {
        // init reference to reader so we can stop it later
        reader = new ContinuousFileReader(file);
        new Thread(reader).start();
    } catch (IOException ioe) {
        // couldn't open file, do something
    }

    // do some other work until ready to shutdown
    reader.stop();
    // wait for reader to stop gracefully, could also add a method to ContinuousReader
    // that takes a timeout value and only waits for that amount of time before shutting
    // down
    try {
        reader.waitForStop();
    } catch (InterruptedException ie) {
        // thread was interrupted, either put this in a loop to continually wait for
        // the reader to stop or ignore this and exit
    }
}

Open in new window

0
 

Author Comment

by:srimallikarthik
ID: 35027218
Experts,
Thanks for the comments/ Help

I tried sample application to resolve my problem using the CreateFile API suggested by "parnasso" and it cleared my question.

@gordon_vt02: thank you for the java code
As  i am coding in C not in java, i couldn't understand it much.
0

Featured Post

Don't lose your head updating email signatures!

Do your end users still have the wrong email signature? Do email signature updates bore you or fill you with a sense of dread? You can make this a whole lot easier on yourself by trusting an Exclaimer email signature management solution. Over 50 million users do...so should you!

Join & Write a Comment

Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
When you start your Windows 10 PC and got an "Operating system not found" error or just saw  "Auto repair for startup". After a while, you have entered a loop for Auto repair which does not fix anything and you will be in a  panic as all your work w…
In this seventh video of the Xpdf series, we discuss and demonstrate the PDFfonts utility, which lists all the fonts used in a PDF file. It does this via a command line interface, making it suitable for use in programs, scripts, batch files — any pl…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

746 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now