Java 프로그램이 C 프로그램과 통신하기를 원합니다. 이것은 간단한 예일뿐입니다. Java 프로그램은 C 프로그램을 실행하고 입력 스트림에 기록해야합니다. C 프로그램은 이것을보고 응답으로 stdout에 써야합니다. 마지막으로 Java 프로그램은 C 프로그램의 stdout에서이 응답을 읽고이를 화면에 인쇄해야합니다.Java에서 stdin/out을 사용하여 C 프로그램과 통신하십시오.
명령 줄에서 C 프로그램을 실행하면 원하는 동작이 나타납니다. 그러나 Java 프로그램에서 실행하면 아무 것도하지 않고 그냥 멈추게됩니다. Java 프로그램은 C 프로그램의 표준에 메시지를 기록한 것으로 보이지만 C 프로그램에서는이 메시지가 표시되지 않습니다.
나는 메시지를 읽는 메시지를 쓰기 위해 C 프로그램을 설정하여 메시지를 읽었는지 확인하고 그렇게하지 않는다. 여기
는 C 프로그램입니다 :#include <stdio.h>
#include <string.h>
void hello();
void wrong();
int main() {
char buff[256];
/* 1. read stdin */
fscanf(stdin, "%s", buff);
/* side effect - if message was received it should be
printed to file */
FILE *fp = fopen("file.txt", "w");
fprintf(fp, "%s", buff);
fclose(fp);
/* 2. depending on message, write something to stdout */
if(strcmp(buff, "hello") == 0) {
hello();
} else {
wrong();
}
}
void hello() {
printf("Hello World!");
}
void wrong() {
printf("WRONG!");
}
그리고 여기에 자바 프로그램입니다 :
내가 메인 실행하면import java.io.*;
public class Main {
public static void main(String[] args) {
try {
// 1. run C program
Process proc = Runtime.getRuntime().exec("./hello");
InputStream in = proc.getInputStream();
OutputStream out = proc.getOutputStream();
// 2. write 'hello' to 'hello' program
writeToProc(out, "hello");
// 3. read response
readFromProc(in);
} catch(Exception e) {
e.printStackTrace();
}
}
// write message to process
public static void writeToProc(OutputStream out, String msg) throws IOException {
byte[] buff = msg.getBytes();
out.write(buff);
out.flush();
System.out.println("done writing: " + new String(buff));
}
// read stdin of process
public static void readFromProc(InputStream in) throws IOException {
byte[] buff = new byte[256];
int read = in.read();
for(int i=0; read != -1; i++) {
read = in.read();
buff[i] = (byte) read;
}
String str = new String(buff);
System.out.println("proc says: " + str);
}
}
, 내가받을 다음과 같은 출력 :
$ java Main
done writing: hello
그리고 C 프로그램이 stdin에서 "hello"를 읽지 못했음을 나타내는 단지 깜박이는 커서와 파일 "file.txt"는 쓰여지지 않습니다.
이것은 간단한 예이므로 뭔가 간단하지 않거나 잘못 입력 한 것 같습니다.
우선 : C 프로그램이나 Java 프로그램에 문제가 있습니까? 그런 다음 작동중인 태그와 코드를 제거하십시오. –
잘 모르겠습니다. Java 프로그램을 추측하고 있지만 잘 모르겠습니다. – Yulek
자, 이제부터 시작하겠습니다. Java 프로그램이 C 프로그램을 호출하면 C 프로그램이 작동합니까? –