Linux的高效的数据传输技术-Relay

http://tech.ddvip.com   2007年02月22日    社区交流

本文详细介绍Linux的高效的数据传输技术-Relay

  ●遍历每一个CPU对应的缓冲文件;

  ●打开文件;

  ●读取所有文件内容;

  ●关闭文件;

  ●最后,umount掉relay文件系统。

  程序内容:

/*
* audience.c
* a user-space client example of relayfs filesystem
*/
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mount.h>
#include <fcntl.h>
#include <sched.h>
#include <errno.h>
#include <stdio.h>
#define MAX_BUFLEN 256
const char filename_base[]="/mnt/relay/cpu";
// implement your own get_cputotal() before compilation
static int get_cputotal(void);
int main(void)
{
    char filename[128]={0};
    char buf[MAX_BUFLEN];
    int fd, c, i, bytesread, cputotal = 0;
    if(mount("relayfs", "/mnt/relay", "relayfs", 0, NULL)
            && (errno != EBUSY)) {
        printf("mount() failed: %s
", strerror(errno));
        return 1;
    }
    cputotal = get_cputotal();
    if(cputotal <= 0) {
        printf("invalid cputotal value: %d
", cputotal);
        return 1;
    }
    for(i=0; i<cputotal; i++) {
        // open per-cpu file
        sprintf(filename, "%s%d", filename_base, i);
        fd = open(filename, O_RDONLY);
        if (fd < 0) {
            printf("fopen() failed: %s
", strerror(errno));
            return 1;
        }
        // read per-cpu file
        bytesread = read(fd, buf, MAX_BUFLEN);
        while(bytesread > 0) {
            buf[bytesread] = '';
            puts(buf);
            bytesread = read(fd, buf, MAX_BUFLEN);
        };
        // close per-cpu file
        if(fd > 0) {
            close(fd);
            fd = 0;
        }
    }
    if(umount("/mnt/relay") && (errno != EINVAL)) {
        printf("umount() failed: %s
", strerror(errno));
        return 1;
    }
    return 0;
}

  上面这个例子给出了使用relay的一个最简单的情形,并没有实际用处,但是形象描述了从用户空间和内核空间两个方面使用relay的基本流程。实际应用中对relay的使用当然要比这复杂得多。

责编:豆豆技术应用

正在加载评论...