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

相关推荐
谢平康几秒前
通过nfs方式做目录限额方法
linux·服务器·网络
I · T · LUCKYBOOM4 分钟前
2.2yum安装--单服务器托管多网站
linux·运维·服务器
龘龍龙7 分钟前
Python基础学习(十)
服务器·python·学习
释怀不想释怀16 分钟前
Linux(复习常见命令)
linux·运维·服务器
2501_9167665425 分钟前
Springboot+vue前后端分离项目部署到云服务器
服务器
礼拜天没时间.31 分钟前
【生产级实战】Linux 集群时间同步详解(NTP + Cron,超详细)
linux·运维·服务器·时间同步·cron·ntp
艾莉丝努力练剑31 分钟前
【Linux进程控制(一)】进程创建是呼吸,进程终止是死亡,进程等待是重生:进程控制三部曲
android·java·linux·运维·服务器·人工智能·安全
NEAI_N32 分钟前
嵌入式 Linux 中 system() 返回值的正确判定
linux·运维·服务器
瀚高PG实验室33 分钟前
无法连接到服务器:连接被拒绝
运维·服务器·瀚高数据库
躲在云朵里`2 小时前
Linux环境下部署SpringBoot前后端分离项目
linux·服务器