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

相关推荐
写代码的【黑咖啡】13 分钟前
Python 中的控制流程:掌握程序的逻辑跳转
服务器·javascript·python
博语小屋17 分钟前
Linux 地址转换函数详解
linux·运维·服务器·c++
YJlio1 小时前
Strings 学习笔记(12.1):从二进制里“扒”出明文信息的瑞士军刀
服务器·笔记·学习
张人玉1 小时前
c#常用的类
服务器·数据库·c#
Suchadar1 小时前
NAT网络地址转换
linux·服务器·网络
翼龙云_cloud1 小时前
阿里云云渠道商:如何选择阿里云 GPU 配置方案?
服务器·人工智能·阿里云·云计算
MarkHD1 小时前
智能体在车联网中的应用:第11天 CARLA自动驾驶仿真入门:从零安装到理解客户端-服务器架构
服务器·架构·自动驾驶
无极小卒2 小时前
Nginx服务器无法访问图片的问题解决
运维·服务器·nginx
txzz88882 小时前
CentOS-Stream-10 YUM第三方库配置
linux·运维·服务器·centos·yum第三方库配置
西格电力科技2 小时前
绿电直连架构适配技术的发展趋势
大数据·服务器·数据库·架构·能源