linux dev设备
/dev目录的文件都是设备,我们可以像操作文件一样操作设备。但是究竟什么才是设备文件哪?作为程序员不能用代码敲出来的概念我们都是不喜欢的,所以本文用shell来操作体验什么才是/dev文件。
我们执行命令的时候,必须有输入设备和输出设备。输入设备对应于/dev/stdin 输出设备对应于/dev/stdout,/dev/stderr。我们通过输出设备来描述/dev的用法。
harvey@ubuntu:/$ ls -l /dev/stdin /dev/stdout /dev/stderr dev/null crw-rw-rw- 1 root root 1, 3 3月 13 2014 dev/null lrwxrwxrwx 1 root root 15 3月 13 2014 /dev/stderr -> /proc/self/fd/2 #shell用2>和2>>表示标准错误输出的元字符 lrwxrwxrwx 1 root root 15 3月 13 2014 /dev/stdin -> /proc/self/fd/0 #shell使用<和<<表示标准输入的元字符 lrwxrwxrwx 1 root root 15 3月 13 2014 /dev/stdout -> /proc/self/fd/1 #shell用>和>>表示标准输出的元字符
直接上代码:重定向
1 harvey@ubuntu:~$ ls #查看文件夹发现存在只是cunzai.txt 2 cunzai.txt 公共的 模板 视频 图片 文档 下载 音乐 桌面 3 harvey@ubuntu:~$ ls -l cunzai.txt bucunzai.txt bcz2.txt #查找存在正确信息和不存在的错误信息都输出到屏幕上 4 ls: 无法访问bucunzai.txt: 没有那个文件或目录 5 ls: 无法访问bcz2.txt: 没有那个文件或目录 6 -rw-rw-r-- 1 harvey harvey 7 3月 13 15:58 cunzai.txt 7 harvey@ubuntu:~$ ls -l cunzai.txt bucunzai.txt bcz2.txt 1>right 2>err #为了验证说法,把正确的信息称定向到right文件,错误信息重定向到err文件 8 harvey@ubuntu:~$ cat right #看出发现right文件中确实是正确的提示 9 -rw-rw-r-- 1 harvey harvey 7 3月 13 15:58 cunzai.txt 10 harvey@ubuntu:~$ cat err #看出err文件中确实为错误的提示 11 ls: 无法访问bucunzai.txt: 没有那个文件或目录 12 ls: 无法访问bcz2.txt: 没有那个文件或目录 13 harvey@ubuntu:~$ ls -l cunzai.txt bucunzai.txt bcz2.txt 1>/dev/null #把正确信息重定向到空设备,让结果只输出错误信息 14 ls: 无法访问bucunzai.txt: 没有那个文件或目录 15 ls: 无法访问bcz2.txt: 没有那个文件或目录 16 harvey@ubuntu:~$ ls -l cunzai.txt bucunzai.txt bcz2.txt 2>/dev/null #把错误信息都称定向到空设备,让结果只输出正确信息 17 -rw-rw-r-- 1 harvey harvey 7 3月 13 15:58 cunzai.txt 18 harvey@ubuntu:~$ ls -l cunzai.txt bucunzai.txt bcz2.txt 2>/dev/null 1>/dev/null #把正确和错误的信息都输出到空设备就不再输出信息
用tcp设备进行socket通讯
1 harvey@ubuntu:~/sh.donotdel$ exec 6<>/dev/tcp/www.baidu.com/80 #打开端口www.baidu.com:80 给该文件一个文件描述符为&6 2 harvey@ubuntu:~/sh.donotdel$ echo -e "HEAD / HTTP/1.1 ">&6 #输入"HEAD /..."信息定向到socket文件&6 3 harvey@ubuntu:~/sh.donotdel$ cat <&6 #导入数据到cat命令 4 HTTP/1.1 302 Moved Temporarily 5 Date: Thu, 13 Mar 2014 08:52:21 GMT 6 Content-Type: text/html 7 Content-Length: 214 8 Connection: Keep-Alive 9 Location: http://www.baidu.com/search/error.html 10 Server: BWS/1.1 11 BDPAGETYPE: 3 12 Set-Cookie: BDSVRTM=0; path=/ 13 Set-Cookie: H_PS_PSSID=; path=/; domain=.baidu.com 14 15 harvey@ubuntu:~/sh.donotdel$ exec 6<&-; #关闭端口 16 harvey@ubuntu:~/sh.donotdel$ exec 6>&- #关闭端口
shell脚本:
1 #!/bin/bash 2 #dev socketdemo 3 #qq 1402115331 4 if($#<2);then 5 echo "请输入两个参数,参数输入有错误!"; 6 exit 1; 7 fi 8 9 exec 6<>/dev/tcp/$1/$2 2>/dev/null; 10 11 if($?!=0);then 12 echo "服务器Socket打开失败,请检查!"; 13 echo 1; 14 fi 15 16 echo -e "HEAD / HTTP/1.1 ">&6; 17 18 cat <&6; 19 exec 6<&-; 20 exec 6>&-;
资料拓展:Linux Shell 通配符、元字符、转义符使用实例介绍
linux shell 脚本实现tcp/upd协议通讯(重定向应用)