Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

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

Posted on 2011-03-01
6
Medium Priority
?
1,145 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 2000 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
Build and deliver software with DevOps

A digital transformation requires faster time to market, shorter software development lifecycles, and the ability to adapt rapidly to changing customer demands. DevOps provides the solution.

 

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

The top UI technologies you need to be aware of

An important part of the job as a front-end developer is to stay up to date and in contact with new tools, trends and workflows. That’s why you cannot miss this upcoming webinar to explore the latest trends in UI technologies!

Question has a verified solution.

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

This article will show how Aten was able to supply easy management and control for Artear's video walls and wide range display configurations of their newsroom.
In this modest contribution, I want to share with the IT community (especially system administrators, IT Support Engineers and IT Help Desks) about Windows crashes/hangs and how to deal with these particular problems.
Simple Linear Regression
Introduction to Processes
Suggested Courses

704 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