在Linux下,每条命令可以通过man命令来获取使用手册。
man命令的使用方法为:man + [要查询的命令]。
示例:
查询man命令的使用手册可以在终端中输入以下指令
man man
1 Executable programs or shell commands // 命令
2 System calls (functions provided by the kernel) // 系统调用,比如 man 2 open
3 Library calls (functions within program libraries) // 函数库调用
4 Special files (usually found in /dev) // 特殊文件, 比如 man 4 tty
5 File formats and conventions eg /etc/passwd // 文件格式和约定, 比如 man 5 passwd
6 Games // 游戏
7 Miscellaneous (including macro packages and conventions), e.g. man(7), groff(7) /
/杂项
8 System administration commands (usually only for root) // 系统管理命令
9 Kernel routines [Non standard] // 内核例程
示例:
我们想查找open函数的用法,open函数是系统调用,所以我们查找的时候可以把序号2加上。
man 2 open
从帮助文档中我们可以看出使用open函数需要包含以下头文件。
#include
#include
#include
在man中含有以下常用的按键和功能。
按键 | 用途 |
---|---|
f | 往下翻一页 |
b | 往上翻一页 |
/ | 从上至下搜 |
? | 从下至上搜 |
q | 离开使用手册 |
使用man 2 open查看需要包含的头文件。
#include
#include
#include
#include
#include
#include
#include
/*
* ./open 1.txt
* argc = 2
* argv[0] = "./open"
* argv[1] = "1.txt"
*/
int main(int argc,char** argv)
{
if(argc != 2)
{
printf("Usage: %s \n" ,argv[0]);
return -1;
}
return 0;
}
在使用printf函数时需要包含头文件
#include
#include
#include
#include
#include
#include
/*
* ./open 1.txt
* argc = 2
* argv[0] = "./open"
* argv[1] = "1.txt"
*/
int main(int argc,char** argv)
{
int fd;
if(argc != 2)
{
printf("Usage: %s \n" ,argv[0]);
return -1;
}
fd = open(argv[1],O_RDWR);
if(fd < 0)
{
printf("can not open file %s\n",argv[1]);
printf("errno :%d\n",errno);
printf("err :%s\n",strerror(errno));
perror("open");
}
else
{
printf("fd = %d\n",fd);
}
return 0;
}
使用open函数打开文件会返回一个文件句柄,如果句柄小于0代表返回错误,对于错误信息输出可以有多种方式。
#include
#include
#include
#include
#include
#include
#include
/*
* ./open 1.txt
* argc = 2
* argv[0] = "./open"
* argv[1] = "1.txt"
*/
int main(int argc,char** argv)
{
int fd;
if(argc != 2)
{
printf("Usage: %s \n" ,argv[0]);
return -1;
}
fd = open(argv[1],O_RDWR);
if(fd < 0)
{
printf("can not open file %s\n",argv[1]);
printf("errno :%d\n",errno);
printf("err :%s\n",strerror(errno));
perror("open");
}
else
{
printf("fd = %d\n",fd);
}
while(1)
{
sleep(10);
}
close(fd);
return 0;
}
gcc -o open ./open.c
./open
./open 1122.txt
./open ./1.txt &
可以看到文件句柄为3,进程为2542。我们可以进入该进程查看里面的所有文件句柄。
cd /proc/2542
ls -l fd