Unix Network Programming Episode 98

复制代码
#include "unp.h"

int my_open(const char *, int);

int main(int argc, char **argv)
{
    int fd, n;
    char buff[BUFFSIZE];

    if(argc!=2)
        err_quit("usage: mycat <pathname>");
    
    if((fd=my_open(argv[1],O_RDONLY))<0)
        err_sys("cannot open %s", argv[1]);
    
    while((n=Read(fd, buff, BUFFSIZE))>0)
        Write(STDOUT_FILENO, buff, n);
    
    return 0;
}

mycat program: copies a file to standard output

复制代码
#include "unp.h"

int my_open(const char *, int);

int my_open(const char *pathname, int mode)
{
    int fd, sockfd[2], status;
    pid_t childpid;
    char c, argsockfd[10], argmode[10];

    Socketpair(AF_LOCAL, SOCK_STREAM, 0, sockfd);

    if((childpid=Fork())==0)
    {
        Close(sockfd[0]);
        snprintf(argsockfd, sizeof(argsockfd),"%d", sockfd[1]);
        snprintf(argmode, sizeof(argmode), "%d", mode);
        execl("./openfile", "openfile", argsockfd, pathname, argmode, (char *)NULL);
        err_sys("execl error");
    }

    Close(sockfd[1]);

    Waitpid(childpid, &status, 0);
    if(WIFEXITED(status)==0)
        err_quit("child did not terminate");
    if((status=WEXITSTATUS(status))==0)
        Read_fd(sockfd[0], &c, 1, &fd);
    else
    {
        errno=status;
        fd=-1;
    }

    Close(sockfd[0]);
    
    return fd;
}

my_open function: opens a file and returns a descriptor

复制代码
在这里插入代码片

read_fd function: receives data and a descriptor

相关推荐
陈陈CHENCHEN2 小时前
【Linux】服务器根目录磁盘扩容操作记录
linux·运维·服务器
沸速存储4 小时前
AI 机器人靠哪些内存与存储驱动整机运行?
服务器·科技·嵌入式硬件·电脑
fengyehongWorld5 小时前
Linux squid搭建基础代理服务器
linux·运维·服务器
Cx330❀6 小时前
【Linux网络】网络层 IP 协议:从网段划分到内核源码解析
大数据·linux·服务器·网络·tcp/ip·性能优化·langchain
一技安身7 小时前
【信创】docker-26.0.2.tgz 原理 + 完整安装
linux·运维·服务器
郝学胜-神的一滴8 小时前
Effective Python 条款 13:善用星号解包,告别下标切片拆分的坑
服务器·开发语言·数据结构·python·程序人生·pycharm
智购无人售货机厂家8 小时前
2026自动售货机品类拓展逻辑:从饮料零食到鲜食药品文创的工程实践~YH
服务器·人工智能·单片机·线性代数·矩阵
国际云,接待9 小时前
华为云 ECS 怎么选规格:从用户地域、CPU/内存比、PPS 和云硬盘性能做购买前容量判断
服务器
国际云,接待9 小时前
华为云 CBR 备份不是点一下就完事:用恢复演练验证 ECS 的 RPO、RTO 和跨区域容灾
服务器
学烹饪的小胡桃9 小时前
资产设备管理系统 WGFIX 怎么设置https访问
linux·运维·服务器·网络·安全