Broken Pipe Java program writing in an external C programs stdin and reading from stdout
I am using the follwing java code to write in the stdin of a C program which basically reads from stdin adds A_A_A to the end of the line and writes it back in the stdout which the java program reaads from and throws the stdout
BufferedWriter b_stdout = new BufferedWriter(new OutputStreamWriter(fuse.process.getOutputStream()));
String strLine;
BufferedReader br = new BufferedReader(new FileReader("/home/Desktop/data1024.dat"));
while ((strLine=br.readLine())!=null)
{
b_stdout.newLine();
b_stdout.write(strLine);
b_stdout.flush();
}
the data1024 file is a text file of size 1 MB. The above is a thread which writes in a C program... following is the C program
main() {
int rc;
int df;
int i;
char buf[32768];
rc = fcntl(fileno(stdin), F_SETFL, O_NONBLOCK);
FILE *fp;
for (i=0;i<=10000000;i++)
{
int rc=-1;
memset(buf,'\0',32768);
//rc = fread(buf,5, 1, stdin);
rc = read(fileno(stdin),buf,32768);
if (rc > 0)
{
strcat(buf,"B_B_B_B_B_B_B_B_B");
write(fileno(stdout),buf,strlen(buf));
/*fp=fopen("wroteExeB","a");
fprintf(fp,"%s",buf);
fclose(fp);*/
//printf("%s",buf);
}
}
Another java thread reads from the stdout of this C program which is following
public void run(){
try{
String strLine;
int c;
BufferedReader bill_stdout = new BufferedReader(new InputStreamReader(fuse.process.getInputStream()));
BufferedWriter new_write = new BufferedWriter(new FileWriter("/homeDesktop/data89.dat"));
while ((strLine = bill_stdout.readLine()) != null) {
new_write.newLine();
new_write.write(strLine);
System.out.println("output thread "+strLine);
new_write.flush();
}
Now when I run the program
I am constabtly facing the Broken:Pipe error
I am able to write some lines into the C program as I can see them in stdout of the input program.
Some lines are part of the output from the output thread but the Input thread which is writing in the C program after few lines like 17 or 18 gives the following error
java.io.IOException: Broken pipe
Could some one help on this... I have tried writing one character at a time using FileWriter and not using BufferedWriter in that case it works and keeps writing characters.
I have tried to reduce the size of the input line that a write... i have tried stoping the input thread so that it could be possible 开发者_如何学编程that the pipes break as they are full and data has not been read. But nothing works
Could some help please. Thanks
I've not looked at the code in detail, but does the C code set stdin to be non-blocking? Won't that just make the C program exit straight away, leading to a broken pipe when you try to write to it?
'Broken pipe' means that you have written to a pipe whose other end is already closed. In other words you have violated the application protocol between you and the receiver. This is not just a matter of buffering, blocking/non-blocking mode etc, it is a design error.
精彩评论