Question

Write a Java program that uses pipes to communicate between processes.

Write a Java program that uses pipes to communicate between processes.
0 0
Add a comment Improve this question Transcribed image text
Answer #1

CODE

import java.io.PipedReader;

import java.io.PipedWriter;

class PipeReaderThread implements Runnable

{

PipedReader pr;

String name = null;

public PipeReaderThread(String name, PipedReader pr)

{

this.name = name;

this.pr = pr;

}

public void run()

{

try {

// continuously read data from stream and print it in console

while (true) {

char c = (char) pr.read(); // read a char

if (c != -1) { // check for -1 indicating end of file

System.out.print(c);

}

}

} catch (Exception e) {

System.out.println(" PipeThread Exception: " + e);

}

}

}

class PipeWriterThread implements Runnable

{

PipedWriter pw;

String name = null;

public PipeWriterThread(String name, PipedWriter pw) {

this.name = name;

this.pw = pw;

}

public void run() {

try {

while (true) {

// Write some data after every two seconds

pw.write("Testing data written...n");

pw.flush();

Thread.sleep(2000);

}

} catch (Exception e) {

System.out.println(" PipeThread Exception: " + e);

}

}

}

public class PipedCommunicationTest

{

public static void main(String[] args)

{

new PipedCommunicationTest();

}

public PipedCommunicationTest()

{

try

{

// Create writer and reader instances

PipedReader pr = new PipedReader();

PipedWriter pw = new PipedWriter();

// Connect the writer with reader

pw.connect(pr);

// Create one writer thread and one reader thread

Thread thread1 = new Thread(new PipeReaderThread("ReaderThread", pr));

Thread thread2 = new Thread(new PipeWriterThread("WriterThread", pw));

// start both threads

thread1.start();

thread2.start();

}

catch (Exception e)

{

System.out.println("PipeThread Exception: " + e);

}

}

}

Add a comment
Know the answer?
Add Answer to:
Write a Java program that uses pipes to communicate between processes.
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT