[android] 关于android的文件描述符(fd)的各种操作的实现

来源:互联网 发布:北方网络视频 编辑:程序博客网 时间:2024/06/01 23:16

 

关键词:jniGetFDFromFileDescriptor, jniSetFileDescriptorOfFD  , jniCreateFileDescriptor

 

java_io_FileDescriptor.c文件在android源码 是找不到的。也许是被封装到 库或者其他类型的文件中去了。

 但是,在android的网站上可以搜到。

实际上,他们的声明位于  libnativehelper/include/nativehelper/JNIHelp.h 。 这样其他代码就可以使用这些函数了。

 

 

 

eclairdalviklibcorelunisrcmainnativejava_io_FileDescriptor.c

 

 

/*
 *  Licensed to the Apache Software Foundation (ASF) under one or more
 *  contributor license agreements.  See the NOTICE file distributed with
 *  this work for additional information regarding copyright ownership.
 *  The ASF licenses this file to You under the Apache License, Version 2.0
 *  (the "License"); you may not use this file except in compliance with
 *  the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
 
#include"JNIHelp.h"

#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<errno.h>
#include<assert.h>
#include<sys/ioctl.h>

/*
 * These are JNI field IDs for the stuff we're interested in.  They're
 * computed when the class is loaded.
 */
staticstruct{
    jfieldID    descriptor;      /* int */
    jmethodID   constructorInt;
    jmethodID   setFD;
    jclass      clazz;
}gCachedFields;

/*
 * Internal helper function.
 *
 * Get the file descriptor.
 */
static inlineintgetFd(JNIEnv* env, jobject obj)
{
    return(*env)->GetIntField(env, obj,gCachedFields.descriptor);
}

/*
 * Internal helper function.
 *
 * Set the file descriptor.
 */
static inlinevoid setFd(JNIEnv* env, jobject obj, jint value)
{
    (*env)->SetIntField(env, obj, gCachedFields.descriptor, value);
}

/*
 * native private static void nativeClassInit()
 *
 * Perform one-time initialization.  If the class is unloaded and re-loaded,
 * this will be called again.
 */
static void nativeClassInit(JNIEnv* env, jclass clazz)
{
    gCachedFields.clazz=(*env)->NewGlobalRef(env, clazz);

    gCachedFields.descriptor=
        (*env)->GetFieldID(env, clazz,"descriptor","I");

    if(gCachedFields.descriptor== NULL){
        jniThrowException(env,"java/lang/NoSuchFieldError","FileDescriptor");
        return;
    }

    gCachedFields.constructorInt=
        (*env)->GetMethodID(env, clazz,"<init>","()V");

    if(gCachedFields.constructorInt== NULL){
        jniThrowException(env,"java/lang/NoSuchMethodError","<init>()V");
        return;
    }
}

/*
 * public native void sync()
 */
static void fd_sync(JNIEnv* env, jobject obj){
    int fd= getFd(env, obj);

    if(fsync(fd)!=0){
        /*
         * If fd is a socket, then fsync(fd) is defined to fail with
         * errno EINVAL. This isn't actually cause for concern.
         * TODO: Look into not bothering to call fsync() at all if
         * we know we are dealing with a socket.
         */
        if(errno!= EINVAL){
            jniThrowException(env,"java/io/SyncFailedException","");
        }
    }
}

/* checks to see if class is inited and inits if needed, returning -1
 * on fail and 0 on success
 */
static int checkClassInit(JNIEnv*env){
    if(gCachedFields.clazz== NULL){
        /* this should cause the class to be inited and
         * our static variables to be filled in
         *
         * (Note that FindClass just loads the class; it doesn't get
         * initialized until we try to do something with it.)
         */
        jclass clazz;
        clazz =(*env)->FindClass(env,"java/io/FileDescriptor");
        if(clazz== NULL){
            jniThrowException(env,"java/lang/ClassNotFoundException",
                                    "java.io.FileDescriptor");
            return-1;
        }

        jfieldID readWriteId;
        readWriteId =(*env)->GetStaticFieldID(env, clazz,"in",
                "Ljava/io/FileDescriptor;");
        if(readWriteId== NULL){
            jniThrowException(env,"java/lang/NoSuchFieldException",
                                    "FileDescriptor.readOnly(Z)");
            return-1;
        }

        (void)(*env)->GetStaticObjectField(env, clazz, readWriteId);
    }

    return0;
}


/*
 * For JNIHelp.c
 * Create a java.io.FileDescriptor given an integer fd
 */

jobject jniCreateFileDescriptor (JNIEnv*env,int fd){
    jobject ret;

    /* the class may not have been loaded yet */
    if(checkClassInit(env)<0){
        return NULL;
    }

    ret =(*env)->NewObject(env, gCachedFields.clazz,
            gCachedFields.constructorInt);
   
    (*env)->SetIntField(env, ret, gCachedFields.descriptor, fd);

    return ret;
}

/*
 * For JNIHelp.c
 * Get an int file descriptor from a java.io.FileDescriptor
 */

intjniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor){
    /* should already be initialized if it's an actual FileDescriptor */
    assert(fileDescriptor!= NULL);
    assert(gCachedFields.clazz!= NULL);

    return getFd(env, fileDescriptor);
}

/*
 * For JNIHelp.c
 * Set the descriptor of a java.io.FileDescriptor
 */

voidjniSetFileDescriptorOfFD(JNIEnv* env, jobject fileDescriptor,int value){
    /* should already be initialized if it's an actual FileDescriptor */
    assert(fileDescriptor!= NULL);
    assert(gCachedFields.clazz!= NULL);

    setFd(env, fileDescriptor, value);
}

/*
 * JNI registration
 */
static JNINativeMethodgMethods[]={
    /* name, signature, funcPtr */
    {"oneTimeInitialization","()V",              nativeClassInit},
    {"syncImpl",          "()V",                 fd_sync}
};
intregister_java_io_FileDescriptor(JNIEnv* env){
    return jniRegisterNativeMethods(env,"java/io/FileDescriptor",
        gMethods, NELEM(gMethods));
}

 

其声明是在 JNIHelp.h 中进行的。

代码所在地址:http://gitorious.org/0xdroid/dalvik/blobs/9892398b7e888ae9792c587fb89b338bfafa6f79/libnativehelper/include/nativehelper/JNIHelp.h

 

/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
/*
 * JNI helper functions.
 *
 * This file may be included by C or C++ code, which is trouble because jni.h
 * uses different typedefs for JNIEnv in each language.
 */
#ifndef _NATIVEHELPER_JNIHELP_H
#define _NATIVEHELPER_JNIHELP_H
 
#include "jni.h"
#include "utils/Log.h"
 
#ifndef NELEM
# define NELEM(x) ((int) (sizeof(x) / sizeof((x)[0])))
#endif
 
#ifdef __cplusplus
extern "C" {
#endif
 
/*
 * Register one or more native methods with a particular class.
 */
int jniRegisterNativeMethods(C_JNIEnv* env, const char* className,
    const JNINativeMethod* gMethods, int numMethods);
 
/*
 * Throw an exception with the specified class and an optional message.
 * The "className" argument will be passed directly to FindClass, which
 * takes strings with slashes (e.g. "java/lang/Object").
 *
 * Returns 0 on success, nonzero if something failed (e.g. the exception
 * class couldn't be found).
 *
 * Currently aborts the VM if it can't throw the exception.
 */
int jniThrowException(C_JNIEnv* env, const char* className, const char* msg);
 
/*
 * Throw a java.lang.RuntimeException, with an optional message.
 */
int jniThrowRuntimeException(JNIEnv* env, const char* msg);
 
/*
 * Throw a java.io.IOException, generating the message from errno.
 */
int jniThrowIOException(C_JNIEnv* env, int errnum);
 
/*
 * Create a java.io.FileDescriptor given an integer fd
 */
jobject jniCreateFileDescriptor(C_JNIEnv* env, int fd);
 
/* 
 * Get an int file descriptor from a java.io.FileDescriptor
 */
int jniGetFDFromFileDescriptor(C_JNIEnv* env, jobject fileDescriptor);
 
/*
 * Set an int file descriptor to a java.io.FileDescriptor
 */
void jniSetFileDescriptorOfFD(C_JNIEnv* env, jobject fileDescriptor, int value);
 
#ifdef __cplusplus
}
#endif
 
 
/*
 * For C++ code, we provide inlines that map to the C functions.  g++ always
 * inlines these, even on non-optimized builds.
 */
#if defined(__cplusplus) && !defined(JNI_FORCE_C)
inline int jniRegisterNativeMethods(JNIEnv* env, const char* className,
    const JNINativeMethod* gMethods, int numMethods)
{
    return jniRegisterNativeMethods(&env->functions, className, gMethods,
        numMethods);
}
inline int jniThrowException(JNIEnv* env, const char* className,
    const char* msg)
{
    return jniThrowException(&env->functions, className, msg);
 }
 inline int jniThrowIOException(JNIEnv* env, int errnum)
 {
     return jniThrowIOException(&env->functions, errnum);
 }
 inline jobject jniCreateFileDescriptor(JNIEnv* env, int fd)
 {
     return jniCreateFileDescriptor(&env->functions, fd);
 }
 inline int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor)
 {
     return jniGetFDFromFileDescriptor(&env->functions, fileDescriptor);
 }
 inline void jniSetFileDescriptorOfFD(JNIEnv* env, jobject fileDescriptor,
     int value)
 {
     return jniSetFileDescriptorOfFD(&env->functions, fileDescriptor, value);
 }
 #endif
 
 #endif /*_NATIVEHELPER_JNIHELP_H*/

 

原创粉丝点击