我在github创建了一个项目,你可以从here.下载
它创建了 2 个命名管道 (FIFO),一个用于输入,另一个用于输出。
它在本地代码中以只写模式打开管道的一端,在 Java 代码中以只读模式打开管道的另一端。本机代码中的文件描述符映射到 STDOUT 即 1,此后在本机代码中对 STDOUT 的任何写入都将被重定向到可以在 Java 代码中读取的管道的另一端。
它在本地代码中以只读模式打开管道的一端,在 Java 代码中以只写模式打开管道的另一端。本机代码中的文件描述符映射到 STDIN 即 0,此后在 Java 代码中对管道另一端的任何写入都将由本机代码使用 STDIN 读取。
实现STDOUT重定向:
本机代码:
/*
* Step 1: Make a named pipe
* Step 2: Open the pipe in Write only mode. Java code will open it in Read only mode.
* Step 3: Make STDOUT i.e. 1, a duplicate of opened pipe file descriptor.
* Step 4: Any writes from now on to STDOUT will be redirected to the the pipe and can be read by Java code.
*/
int out = mkfifo(outfile, 0664);
int fdo = open(outfile, O_WRONLY);
dup2(fdo, 1);
setbuf(stdout, NULL);
fprintf(stdout, "This string will be written to %s", outfile);
fprintf(stdout, "\n");
fflush(stdout);
close(fdo);
Java 代码:
/*
* This thread is used for reading content which will be written by native code using STDOUT.
*/
new Thread(new Runnable() {
@Override
public void run() {
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader(mOutfile));
while(in.ready()) {
final String str = in.readLine();
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(RedirectionJni.this, str, Toast.LENGTH_LONG).show();
}
});
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
实现STDIN重定向:
本机代码:
/*
* Step 1: Make a named pipe
* Step 2: Open the pipe in Read only mode. Java code will open it in Write only mode.
* Step 3: Make STDIN i.e. 0, a duplicate of opened pipe file descriptor.
* Step 4: Any reads from STDIN, will be actually read from the pipe and JAVA code will perform write operations.
*/
int in = mkfifo(infile, 0664);
int fdi = open(infile, O_RDONLY);
dup2(fdi, 0);
char buf[256] = "";
fscanf(stdin, "%*s %99[^\n]", buf); // Use this format to read white spaces.
close(fdi);
Java 代码:
/*
* This thread is used for writing content which will be read by native code using STDIN.
*/
new Thread(new Runnable() {
@Override
public void run() {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(mInfile)));
String content = "This content is written to " + mInfile;
out.write(content.toCharArray(), 0, content.toCharArray().length);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
如果您需要任何帮助,请告诉我。