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

相关推荐
Wy_编程41 分钟前
Linux-文本搜索工具grep
linux·运维·服务器
qq9989942 分钟前
AAA服务器技术
运维·服务器
xujiangyan_44 分钟前
linux的sysctl系统以及systemd系统。
linux·服务器·网络
Lovyk1 小时前
Linux Shell 常用操作与脚本示例详解
linux·运维·服务器
iCan_qi1 小时前
【Mac】【Minecraft】关于如何在Mac上搭建基岩版MC服务器的方法
运维·服务器·macos·minecraft
xixingzhe24 小时前
多人同时导出 Excel 导致内存溢出
服务器·设计
云手机掌柜4 小时前
Tumblr长文运营:亚矩阵云手机助力多账号轮询与关键词布局系统
大数据·服务器·tcp/ip·矩阵·流量运营·虚幻·云手机
云边云科技5 小时前
零售行业新店网络零接触部署场景下,如何选择SDWAN
运维·服务器·网络·人工智能·安全·边缘计算·零售
AOwhisky6 小时前
Linux 文本处理三剑客:awk、grep、sed 完全指南
linux·运维·服务器·网络·云计算·运维开发
runfarther7 小时前
搭建LLaMA-Factory环境
linux·运维·服务器·python·自然语言处理·ai编程·llama-factory