Solved

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

Posted on 2011-03-01
6
1,139 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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 31

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
Portable, direct connect server access

The ATEN CV211 connects a laptop directly to any server allowing you instant access to perform data maintenance and local operations, for quick troubleshooting, updating, service and repair.

 

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

Announcing the Most Valuable Experts of 2016

MVEs are more concerned with the satisfaction of those they help than with the considerable points they can earn. They are the types of people you feel privileged to call colleagues. Join us in honoring this amazing group of Experts.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Configuring Remote Assistance for use with SCCM
I was prompted to write this article after the recent World-Wide Ransomware outbreak. For years now, System Administrators around the world have used the excuse of "Waiting a Bit" before applying Security Patch Updates. This type of reasoning to me …
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …

751 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