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

相关推荐
鳄鱼杆19 分钟前
服务器 | Centos 9 系统中,如何部署SpringBoot后端项目?
服务器·spring boot·centos
weixin_461259412 小时前
[C]C语言日志系统宏技巧解析
java·服务器·c语言
m0_637146932 小时前
C语言基础面试问答
运维·服务器
Clownseven2 小时前
SSH/RDP无法远程连接?腾讯云CVM及通用服务器连接失败原因与超全排查指南
服务器·ssh·腾讯云
ricky_fan2 小时前
window下配置ssh免密登录服务器
运维·服务器·ssh
2401_858286113 小时前
OS11.【Linux】vim文本编辑器
linux·运维·服务器·编辑器·vim
朱包林3 小时前
day27-shell编程(自动化)
linux·运维·服务器·网络·shell脚本
layman05283 小时前
OpenEuler服务器警告邮件自动化发送:原理、配置与安全实践
服务器·鸿蒙系统·openeuler
小阳睡不醒4 小时前
小白成长之路-Linux Shell脚本练习
linux·运维·服务器
知之则吱吱5 小时前
亚马逊AWS云服务器高效使用指南:最大限度降低成本的实战策略
服务器·云计算·aws