基础IO

>* 练习open/read/write/close等文件相关系统调用接口,纵向对比fdFILE结构体 

#include <sys/types.h>,#include <sys/stat.h>,#include <fcntl.h>

答:

       Open 函数:

              Int   open    (const char * pathname , int flag)

              参数pathname 指的是文件路径字符串

              Flag 指的是文件的打开方式

              O_RDONLY 以只读方式打开

              O-WRONLY 以只写方式打开

              O_RDWR   以读写的方式打开

              成功返回文件标识符,失败返回-1

       Write 函数:

              Ssize_t write (int fd ,const void * buf ,size_t count)

              Int fd  往哪写一般为一个文件标识符

              Buf   写什么  是一段缓冲区

              Count 要写的字符的个数

              成功返回写入的字节数,失败返回-1

       Read 函数:

              Ssize_t write(int fd , const void * buf  , size_t count)

              Fd 为读取的文件的文件标识符

              Buf 为缓冲区

              Count 为期望读取的字节数

              成功返回读取的字节数,失败返回-1

 

       在man手册上close的函数原型是:

int close(int fd);

该函数只有一个参数,参数表示文件标识符,

返回值:返回0表示成功,返回-1表示失败

 

 

       fd和FILE对比。

fd属于系统库,FILE属于c标准库,fd是一个整数,FILE是一个结构体,

 

             

 


>* 对之前编写的自主shell进行修改,使其支持输入/输出/追加重定向

 

1 #include<stdio.h>                                                              
  2 #include<stdlib.h>
  3 #include<sys/types.h>
  4 #include<sys/wait.h>
  5 #include<unistd.h>
  6 int main ()
  7 {
  8     char cmd [128];
  9     while(1)
 10     {
 11       printf("[user@localhost myshell]$ ");
 12       fflush(stdout);
 13       ssize_t s=read(0,cmd,sizeof(cmd)-1);
 14      if(s>0)
15      {  
 16       cmd[s-1]=0;
 17      }
 18      else
 19      {
 20        perror("read");
 21        return -1;
 22      }
 23      char * argv[32];
 24      int i=1;
 25      argv[0]=cmd;
 26      char * start=cmd;
 27      while(*start)   
28      {
 29        if(isspace(*start))
 30        {
 31         *start='\0';
 32         start++;
 33         argv[i]=start;
 34         i++;
 35         continue;
 36        }
 37        start++;
 38      }
 39     argv[i]=NULL;
 40     pid_t id=fork(); 
41     if(id>0)
 42     {
 43      //父进程
 44      int status=0;
 45     int ret= waitpid(id,&status,0);
 46      if(ret>0&&WIFEXITED(status))
 47      {
 48        {}
 49      }
 50      else
 51      {
 52        perror("waitpid");
 53      }            
54 
 55     }
 56     else if(0==id)
 57     {
 58       //子进程
 59       execvp(argv[0],argv);
 60       exit(1);
 61     }
 62     
 63     else
 64     perror("fork");
 65 }
 66   return 0; 
 67 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值