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

相关推荐
能不能别报错3 小时前
openclaw-linux部署教程+mimo-v2-pro
linux·运维·服务器
钛态5 小时前
Flutter for OpenHarmony:mockito 单元测试的替身演员,轻松模拟复杂依赖(测试驱动开发必备) 深度解析与鸿蒙适配指南
服务器·驱动开发·安全·flutter·华为·单元测试·harmonyos
硅基导游6 小时前
Linux内核观测与跟踪的利器BPF环境测试
linux·服务器·性能监控·bpf
我是谁??7 小时前
在 Rocky Linux 9 无桌面环境中通过 SSH 安装 KVM 虚拟机(Rocky9含 XFCE 桌面/xubuntu20)完整指南
linux·服务器·ssh
Luke Ewin7 小时前
Linux中部署Qwen3.5大模型
linux·运维·服务器·ai·llm·qwen3.5
春日见8 小时前
云服务器开发与SSH
运维·服务器·人工智能·windows·git·自动驾驶·ssh
minji...8 小时前
Linux 进程间通信(三)命名管道
linux·服务器·网络
还是做不到嘛\.8 小时前
DVWA靶场-Brute Force
运维·服务器·数据库·学习
克莱因3588 小时前
linux主机名与Hosts映射 (顺带个DNS简介
linux·运维·服务器