IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 系统运维 -> android 通信之 BitTube -> 正文阅读

[系统运维]android 通信之 BitTube

AOSP中使用BitTube 的地方有显示(Display)子系统和Sensor子系统,在这里一探究竟

1. 概述

BitTube是用来处理进程间通讯的机制,和管道类似,主要是socketpair的封装,

2 socketpair

socketpair用来创建一堆未命名的,互相连接的套接字,套接字一端可以进行读写操作,用来实现全双工的通讯。

函数原型 int socketpair(int domain, int type, int protocol, int sv[2]);

  • domain 在linux平台上只能使用AF_UNIX
  • type表示socket的类型,目前支持如下类型
  • protocol 目前必须为0
  • sv[2] 代表两个互相连接的套接字
/**
 * enum sock_type - Socket types
 * @SOCK_STREAM: stream (connection) socket
 * @SOCK_DGRAM: datagram (conn.less) socket
 * @SOCK_RAW: raw socket
 * @SOCK_RDM: reliably-delivered message
 * @SOCK_SEQPACKET: sequential packet socket
 * @SOCK_DCCP: Datagram Congestion Control Protocol socket
 * @SOCK_PACKET: linux specific way of getting packets at the dev level.
 *                For writing rarp and other similar things on the user level.
 *
 * When adding some new socket type please
 * grep ARCH_HAS_SOCKET_TYPE include/asm-* /socket.h, at least MIPS
 * overrides this enum for binary compat reasons.
 */

3 socketpair用法

//test in ubuntu 14.04 by helenxr
//step1:gcc socketpair.c
//step2:./a.out

/*test result like below:
create socketpair[3,4]
child process rcv msg:parent send to child.
parent rcv msg:parent send to child.
child process rcv msg:parent send to child.
parent rcv msg:parent send to child.
child process rcv msg:parent send to child.
parent rcv msg:parent send to child.
child process rcv msg:parent send to child.
parent rcv msg:parent send to child.
child process rcv msg:parent send to child.
parent rcv msg:parent send to child.
*/
#include <sys/types.h>          
#include <sys/socket.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

int main(){
    int sockets[2];
    unsigned char loop_cnt_p = 5,loop_cnt_c = 5;

    if(socketpair(AF_UNIX,SOCK_SEQPACKET,0,sockets) == 0) {
        printf("create socketpair[%d,%d]\n",sockets[0],sockets[1]);
    }else {
        printf("create socketpair error.\n");
        return -1;
    }

  //create process
  if(fork()){ //parent
    while(loop_cnt_p--){
        char parent_rcv_buf[100] = "";
        char parent_send_buf[] = "parent send to child.";
        if(write(sockets[1],parent_send_buf,sizeof(parent_send_buf)) < 0){
            printf("parent write buffer error!\n");
            return -1;
        }
        if(read(sockets[1],parent_rcv_buf,sizeof(parent_rcv_buf)) < 0){
            printf("parent read buffer error!\n");
            return -1;
        }else{
            printf("parent rcv msg:%s\n",parent_rcv_buf);
        }          
        sleep(2); 
    }
  }else{//child
      while(loop_cnt_c--){        
          char child_rcv_buf[100] = "";
          char child_send_buf[] = "clild send to parent.";
          if(read(sockets[0],child_rcv_buf,sizeof(child_rcv_buf)) < 0){
              printf("clild read buffer error!\n");
              return -1;
          }else{
              printf("child process rcv msg:%s\n",child_rcv_buf);
          }
          if(write(sockets[0],child_rcv_buf,sizeof(child_rcv_buf)) < 0){
              printf("child write buffer error!\n");
              return -1;
          }          
          sleep(2);
        }
  }


  close(sockets[0]);
  close(sockets[1]);
  return 0;
}

4 BitTube

BitTube代码量很少,在(frameworks\native\libs\gui\BitTube.cpp)中,我们直接看它的几个重要的接口.

//frameworks/native/include/gui/BitTube.h
namespace android {
// ----------------------------------------------------------------------------
class Parcel;

class BitTube : public RefBase
{
public:

    // creates a BitTube with a default (4KB) send buffer
    BitTube();

    // creates a BitTube with a a specified send and receive buffer size
    explicit BitTube(size_t bufsize);

    explicit BitTube(const Parcel& data);
    virtual ~BitTube();

    // check state after construction
    status_t initCheck() const;

    // get receive file-descriptor
    int getFd() const;

    // get the send file-descriptor.
    int getSendFd() const;

    // send objects (sized blobs). All objects are guaranteed to be written or the call fails.
    template <typename T>
    static ssize_t sendObjects(const sp<BitTube>& tube,
            T const* events, size_t count) {
        return sendObjects(tube, events, count, sizeof(T));
    }

    // receive objects (sized blobs). If the receiving buffer isn't large enough,
    // excess messages are silently discarded.
    template <typename T>
    static ssize_t recvObjects(const sp<BitTube>& tube,
            T* events, size_t count) {
        return recvObjects(tube, events, count, sizeof(T));
    }

    // parcels this BitTube
    status_t writeToParcel(Parcel* reply) const;

private:
    void init(size_t rcvbuf, size_t sndbuf);

    // send a message. The write is guaranteed to send the whole message or fail.
    ssize_t write(void const* vaddr, size_t size);

    // receive a message. the passed buffer must be at least as large as the
    // write call used to send the message, excess data is silently discarded.
    ssize_t read(void* vaddr, size_t size);

    int mSendFd;
    mutable int mReceiveFd;

    static ssize_t sendObjects(const sp<BitTube>& tube,
            void const* events, size_t count, size_t objSize);

    static ssize_t recvObjects(const sp<BitTube>& tube,
            void* events, size_t count, size_t objSize);
};

// ----------------------------------------------------------------------------
}; 
//frameworks/native/libs/gui/BitTube.cpp
namespace android {
// ----------------------------------------------------------------------------

// Socket buffer size.  The default is typically about 128KB, which is much larger than
// we really need.  So we make it smaller.
static const size_t DEFAULT_SOCKET_BUFFER_SIZE = 4 * 1024;


BitTube::BitTube()
    : mSendFd(-1), mReceiveFd(-1)
{
    init(DEFAULT_SOCKET_BUFFER_SIZE, DEFAULT_SOCKET_BUFFER_SIZE);
}

BitTube::BitTube(size_t bufsize)
    : mSendFd(-1), mReceiveFd(-1)
{
    init(bufsize, bufsize);
}

BitTube::BitTube(const Parcel& data)
    : mSendFd(-1), mReceiveFd(-1)
{
    mReceiveFd = dup(data.readFileDescriptor());
    if (mReceiveFd < 0) {
        mReceiveFd = -errno;
        ALOGE("BitTube(Parcel): can't dup filedescriptor (%s)",
                strerror(-mReceiveFd));
    }
}

BitTube::~BitTube()
{
    if (mSendFd >= 0)
        close(mSendFd);

    if (mReceiveFd >= 0)
        close(mReceiveFd);
}

//创建/配置socketpair.
void BitTube::init(size_t rcvbuf, size_t sndbuf) {
    int sockets[2];
    //创建socketpair
    if (socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets) == 0) {
        size_t size = DEFAULT_SOCKET_BUFFER_SIZE;
         //对socketfd进行配置
        setsockopt(sockets[0], SOL_SOCKET, SO_RCVBUF, &rcvbuf, sizeof(rcvbuf));
        setsockopt(sockets[1], SOL_SOCKET, SO_SNDBUF, &sndbuf, sizeof(sndbuf));
        // sine we don't use the "return channel", we keep it small...
        setsockopt(sockets[0], SOL_SOCKET, SO_SNDBUF, &size, sizeof(size));
        setsockopt(sockets[1], SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
        //设置为非阻塞模式
        fcntl(sockets[0], F_SETFL, O_NONBLOCK);
        fcntl(sockets[1], F_SETFL, O_NONBLOCK);
        //成员变量mReceiveFd,看起来是一个接收端,实际上这个fd也可以用来发送
        //mSendFd也可以用来接收
        mReceiveFd = sockets[0];
        mSendFd = sockets[1];
    } else {
        mReceiveFd = -errno;
        ALOGE("BitTube: pipe creation failed (%s)", strerror(-mReceiveFd));
    }
}

status_t BitTube::initCheck() const
{
    if (mReceiveFd < 0) {
        return status_t(mReceiveFd);
    }
    return NO_ERROR;
}

int BitTube::getFd() const
{
    return mReceiveFd;
}

int BitTube::getSendFd() const
{
    return mSendFd;
}

//调用send接口将数据写入mSendFd中(send与write类似,与write相比多了第四个参数,用来做标志控制)
ssize_t BitTube::write(void const* vaddr, size_t size)
{
    ssize_t err, len;
    do {
        len = ::send(mSendFd, vaddr, size, MSG_DONTWAIT | MSG_NOSIGNAL);
        // cannot return less than size, since we're using SOCK_SEQPACKET
        err = len < 0 ? errno : 0;
    } while (err == EINTR);
    return err == 0 ? len : -err;
}
//read中调用recv接口将数据从mReceiveFd中读出(recv与read类似,与read相比,多了第四个参数,用来做标志控制)
ssize_t BitTube::read(void* vaddr, size_t size)
{
    ssize_t err, len;
    do {
        len = ::recv(mReceiveFd, vaddr, size, MSG_DONTWAIT);
        err = len < 0 ? errno : 0;
    } while (err == EINTR);
    if (err == EAGAIN || err == EWOULDBLOCK) {
        // EAGAIN means that we have non-blocking I/O but there was
        // no data to be read. Nothing the client should care about.
        return 0;
    }
    return err == 0 ? len : -err;
}

status_t BitTube::writeToParcel(Parcel* reply) const
{
    if (mReceiveFd < 0)
        return -EINVAL;

    status_t result = reply->writeDupFileDescriptor(mReceiveFd);
    close(mReceiveFd);
    mReceiveFd = -1;
    return result;
}

//sendObjects里调用的是write成员函数
ssize_t BitTube::sendObjects(const sp<BitTube>& tube,
        void const* events, size_t count, size_t objSize)
{
    const char* vaddr = reinterpret_cast<const char*>(events);
    ssize_t size = tube->write(vaddr, count*objSize);

    // should never happen because of SOCK_SEQPACKET
    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % static_cast<ssize_t>(objSize)),
            "BitTube::sendObjects(count=%zu, size=%zu), res=%zd (partial events were sent!)",
            count, objSize, size);

    //ALOGE_IF(size<0, "error %d sending %d events", size, count);
    return size < 0 ? size : size / static_cast<ssize_t>(objSize);
}
//recvObjects里调用read成员函数
ssize_t BitTube::recvObjects(const sp<BitTube>& tube,
        void* events, size_t count, size_t objSize)
{
    char* vaddr = reinterpret_cast<char*>(events);
    ssize_t size = tube->read(vaddr, count*objSize);

    // should never happen because of SOCK_SEQPACKET
    LOG_ALWAYS_FATAL_IF((size >= 0) && (size % static_cast<ssize_t>(objSize)),
            "BitTube::recvObjects(count=%zu, size=%zu), res=%zd (partial events were received!)",
            count, objSize, size);

    //ALOGE_IF(size<0, "error %d receiving %d events", size, count);
    return size < 0 ? size : size / static_cast<ssize_t>(objSize);
}

// ----------------------------------------------------------------------------
}; 

5 andorod 中 BitTube应用-sensor

@service/SensorEventConnection.cpp
status_t SensorService::SensorEventConnection::sendEvents(
        sensors_event_t const* buffer, size_t numEvents,
        sensors_event_t* scratch,
        wp<const SensorEventConnection> const * mapFlushEventsToConnections) {
    ...
    // NOTE: ASensorEvent and sensors_event_t are the same type.
    ssize_t size = SensorEventQueue::write(mChannel,
                                    reinterpret_cast<ASensorEvent const*>(scratch), count);    //write mChannel
}
 
@frameworks/native/libs/sensor/SensorEventQueue.cpp
ssize_t SensorEventQueue::write(const sp<BitTube>& tube,
        ASensorEvent const* events, size_t numEvents) {
    return BitTube::sendObjects(tube, events, numEvents);
}

  系统运维 最新文章
配置小型公司网络WLAN基本业务(AC通过三层
如何在交付运维过程中建立风险底线意识,提
快速传输大文件,怎么通过网络传大文件给对
从游戏服务端角度分析移动同步(状态同步)
MySQL使用MyCat实现分库分表
如何用DWDM射频光纤技术实现200公里外的站点
国内顺畅下载k8s.gcr.io的镜像
自动化测试appium
ctfshow ssrf
Linux操作系统学习之实用指令(Centos7/8均
上一篇文章      下一篇文章      查看所有文章
加:2022-05-07 11:29:31  更:2022-05-07 11:31:45 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/15 17:19:48-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码