2017-04-23 11 views
0

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"는 쓰여지지 않습니다.

이것은 간단한 예이므로 뭔가 간단하지 않거나 잘못 입력 한 것 같습니다.

+1

우선 : C 프로그램이나 Java 프로그램에 문제가 있습니까? 그런 다음 작동중인 태그와 코드를 제거하십시오. –

+0

잘 모르겠습니다. Java 프로그램을 추측하고 있지만 잘 모르겠습니다. – Yulek

+0

자, 이제부터 시작하겠습니다. Java 프로그램이 C 프로그램을 호출하면 C 프로그램이 작동합니까? –

답변

3

문제는 당신이 fscanf"press enter"에 프로세스가 무한정 기다리고 계속하여 자바에서 보내는 문자열에 새로운 라인 문자 \n을 (공백이 트릭을 할해야합니다)를 추가하는 것을 잊었다는 것이다. 나는 코드를 약간 수정했고 변경 사항은 주석에 문서화되어있다.

import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 

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 
      // <change> 
      // don't forget to add the new line here or in the 
      // writeToProc method 
      writeToProc(out, "hello\n"); 
      // 3. read response 
      readFromProc(in); 
     } catch(Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    // write message to process 
    public static void writeToProc(OutputStream out, String msg) throws IOException { 
     // <change> 
     // Using UTF-8 encoding since all chars in C are byte sized 
     byte[] buff = msg.getBytes("UTF-8"); 
     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(); 
     int index = 0; 
     while(read != -1) { 
      buff[index] = (byte) read; 
      read = in.read(); 
      ++index; 
     } 
     String str = new String(buff, 0, index); 
     System.out.println("proc says: " + str); 
    } 
} 
+0

'new String (buff, 0, index)'를 사용하여 버퍼의 유효 부분 만 변환하는 경우 배열 복사본이 필요하지 않습니다. (또한 남은 요소는 유니 코드를 포함하여 ASCII 호환 코드에서 0x30 aka 48 인'char '0'이 아니라'-b '값 0이 보이지 않을 때 보이지 않습니다. –

+0

@ dave_thompson_085 입력 해 주셔서 감사합니다. 'new String (buff, 0, index)'생성자를 생각해 보라. 후행 0에 관해서는, 나는 그들이 보이지 않을 것이라는 점을 또한 생각했다. 그러나 그들은 일식에서 나타났다, 나는 그들이 "진짜"콘솔에 나타나지 않을지도 모른다라고 생각한다. 그러나 그것을 시험해 보지 않았다. 나는'new String (buff, 0, index)'해결책을 좋아했고, 그 접근법을 사용하기 위해 나의 대답을 업데이트했다. 감사! – StaticBeagle