《linux程序设计学习笔记》之一---几个常用的目录和底层调用

在linux中,几乎一切都是文件。

三个设备(目录):

1. /dev/console

此设备代表系统控制台,错误消息和诊断信息通常会发往这个设备,每个unix(like)系统都会有一个指定的的终端或显示屏来接受控制台消息。

2./dev/tty

如果一个进程有控制终端的话,那么特殊文件/dev/tty就是这个控制终端的别名,例如由系统自动运行的进程和脚本就没有控制终端,所以他们不能打开dev/tty,在能够使用该设备文件的情况下,/dev/tty允许程序直接向用户输出信息,而不管用户使用的是哪种类型的伪终端或硬件终端。在标准输出被重定向时,这一功能变得非常有用。

3./dev/null

空设备,即可认为是回收站。所有写向这个设备的输出都将被丢弃,而读这个设备会立刻返回一个文件尾标志,所以在cp命令里可以把它用作复制空文件的源文件。一般的用途是把不需要的输出重定向到/dev/null。

例:

echo do not want to see this  >  /dev/null

cp /dev/null empty_file  与 touch empty_file 作用几乎相同(在文件已存在的情况下 touch会修改文件的修改时间,但不能把有内容的文件变为空文件)。


几个常用的系统调用:

1.write系统调用

#include <unistd.h>

size_t write(int fildes, const void *buf ,size_t nbytes);

正常情况下该函数返回nbytes,某些情况(文件描述符有错或者底层设备驱动对数据块长度比较敏感)返回值小于nbytes,如果返回0,则表示未写入任何数据;若返回-1,就表示write调用出错。错误代码保存在errno中。

程序用例:

  1 #include<unistd.h>
  2 #include<stdlib.h>
  3 
  4 int main()
  5 {
  6     if ((write(1,"here is some data\n",18)) != 18)
  7         write(2,"a write error has occurred on file descriptor 1\n",46);
  8 
  9     return 0;
 10 }

运行时 输出 here is some data

2.read系统调用

#include <unistd.h>

size_t read(int fildes,void *buf,size_t nbytes);

它会返回实际读入的字节数,这可能会小于请求的字节数。若返回0,表示未读入任何数据,已到达文件尾。若返回-1,说明read调用出错。

程序用例:

  1 #include<unistd.h>
  2 #include<stdlib.h>
  3 
  4 int main()
  5 {
  6     char buffer[128];
  7     int nread;
  8     nread = read(0,buffer,128);
  9     if (nread == -1 )
 10         write(2,"A read error has occurred\n",26);
 11     if ((write(1,buffer,nread)) != nread)
 12         write(2,"A write error has occurred\n",27);
 13 
 14     exit(0);
 15 }

运行 echo hello world!  | ./read

或者 ./read  < 123.txt


3.open系统调用

#include <fcntl.h>

#include <sys/types.h>

#include <sys/stat.h>

int open(const char *path,int oflags);

int open(const char *path,int oflags,mode_t mode);

open建立了一条到文件或者设备的访问路径。他返回的文件描述符可以被read ,write和其他的系统调用所使用。open调用经常用来打开或者创建文件。

程序用例:

  1 #include<unistd.h>
  2 #include<fcntl.h>
  3 #include<sys/stat.h>
  4 #include<stdlib.h>
  5 
  6 int main()
  7 {
  8     char c;
  9     int in ,out;
 10     in = open("file.in",O_RDONLY);
 11     out = open ("file.out",O_WRONLY|O_CREAT,0644);
 12     while (read(in,&c,1) == 1);
 13         write(out,&c,1);
 14     exit(0);
 15 }

O_WRONLY|O_CREAT表示创建文件且文件权限未只写,umask值为0644,即,-rw-r--r--


4.close系统调用

#include <unistd.h>

int close(int fildes);

释放文件描述符,成功返回0,出错返回-1。

此调用的返回结果有时显得非常重要,在程序中尽可能的使用它。




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值