Android - 在原生应用和Java应用之间使用管道

4
我正在使用SGS2 api v.16进行开发。
我有两个应用程序:本地应用和Java应用。
在本地应用中,我使用mkfifo()函数打开一个Unix管道并向其中写入一些字符串。
而在Java应用中,我尝试读取这个字符串,但是应用程序阻塞了,我不知道为什么,在logcat中也没有任何指示说明它为什么会阻塞。
这两个应用程序在manifest文件中都有android:sharedUserId="my.Id",并且共享已经成功。
在logcat中,我可以看到“opening input stream”的日志,但之后没有其他日志了。是否有推荐的方法来从Java中的管道文件中读取数据? 注意:如果我使用open(...)打开普通文件而不是使用mkfifo(...),我可以成功地从文件中读取数据,问题只出现在我使用mkfifo()打开管道文件时。 以下是从本地应用程序运行的函数:
jint Java_com_example_ndkfoo_NdkFooActivity_writeToPipe(JNIEnv* env, jobject javaThis) {
   const char* PATH = "/data/data/com.example.ndkfoo/v_pipe8";
   char* line = "Hello Pipe!";
   int pipe;
   errno = 0;

   // open a named pipe
   mode_t mode = S_IRWXU | S_IRWXG | S_IRWXO;
   pipe = mkfifo(PATH, mode);
   if(errno != 0) {
        __android_log_write(ANDROID_LOG_ERROR, "NDK_FOO_TAG", strerror(errno));
        return errno;
    }
    __android_log_write(ANDROID_LOG_DEBUG, "NDK_FOO_TAG", "file opened successfully");

   // actually write out the data and close the pipe
   int err = write(pipe, line, strlen(line));

    // close the pipe
   close(pipe);
   return err;

}

这里是尝试从管道中读取的Java代码

package com.example.secondparty;

import java.io.FileDescriptor;
import java.io.FileInputStream;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;

public class MainActivity extends Activity {
     private static final String TAG = MainActivity.class.getSimpleName();
     //public final static String PATH2 = "/sdcard/fifo9001";
     public final static String PATH = "/data/data/com.example.ndkfoo/v_pipe8";

     @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        readFromPipe();

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    private void readFromPipe() {
        Log.i(TAG, "Attempt started");
        FileInputStream fis;
        String message = "";
        byte buffer[] = new byte[256];

        try {
            Log.i(TAG, "openning input stream");
            fis = new FileInputStream(PATH);
            Log.i(TAG, "input stream opened");
            FileDescriptor fd =  fis.getFD();
            int len = 0;
            do {
                len = fis.read(buffer);
                if(len > 0) {
                    String newmessage = new String(buffer,0, len, "US-ASCII");
                    message += newmessage;
                }
            } while (len == buffer.length);
            Log.i(TAG, "message: "+message);
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}

我假设它在do..while循环中阻塞了? - Simon
2个回答

1
使用 BufferedReader 替代 `FileInputStream`。

嗨,我尝试了你的方法,但是在 BufferedReader 中总是等待。 - CLIFFORD P Y

0

加班,链接可能会失效。请在您的答案中包含所有细节。此问题已有一个被接受的答案,请注意。 - SaggingRufus

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接