在 Linux 系统中,“函数”这个概念通常有两个层面的含义,容易混淆,为了给你最准确的介绍,我将分别从 Shell 脚本编程中的函数 和 C 语言系统调用/库函数(即 Linux API) 两个角度进行详细介绍。
Shell 脚本中的函数(Shell Functions)
在 Bash、Zsh 等 Shell 脚本中,函数是一段可重复使用的代码块,用于封装逻辑,提高脚本的可读性和复用性。
函数定义语法
# 方式一:标准写法(推荐)
function_name() {
command1
command2
# ...
}
# 方式二:带 function 关键字
function function_name {
command1
command2
}
调用函数
直接通过函数名调用即可:
my_function
传递参数
Shell 函数通过位置参数 $1, $2, … 接收参数, 表示参数个数, 或 表示所有参数。
greet() {
echo "Hello, $1!"
}
greet "Alice" # 输出: Hello, Alice!
返回值
- 退出状态码:函数默认返回最后一条命令的退出状态(0 表示成功,非 0 表示失败)。
- 使用
return:可以显式返回一个整数状态码(0–255)。 - 输出结果:若需返回字符串或复杂数据,通常通过
echo输出,调用者通过命令替换捕获:
get_result() {
echo "success"
}
result=$(get_result)
echo "Result: $result" # 输出: Result: success
局部变量
使用 local 关键字声明局部变量,避免污染全局环境:
my_func() {
local var="local value"
echo "$var"
}
示例:完整函数示例
#!/bin/bash
# 定义函数
check_file() {
local file=$1
if [ -f "$file" ]; then
echo "File $file exists."
return 0
else
echo "File $file not found."
return 1
fi
}
# 调用函数
check_file "/etc/passwd"
check_file "/nonexistent"
Linux 系统编程中的函数(C 语言 API)
在 Linux 系统编程中,“函数”通常指 系统调用(System Calls) 或 C 标准库/POSIX 库函数,用于与内核交互或执行标准操作。
系统调用(System Calls)
系统调用是用户空间程序请求内核服务的接口。
| 函数名 | 头文件 | 功能简述 |
|---|---|---|
open() |
<fcntl.h> |
打开或创建文件 |
read() |
<unistd.h> |
从文件描述符读取数据 |
write() |
<unistd.h> |
向文件描述符写入数据 |
close() |
<unistd.h> |
关闭文件描述符 |
fork() |
<unistd.h> |
创建子进程 |
exec() 系列 |
<unistd.h> |
执行新程序 |
wait() |
<sys/wait.h> |
等待子进程结束 |
socket() |
<sys/socket.h> |
创建网络套接字 |
bind() |
<sys/socket.h> |
绑定套接字地址 |
listen() |
<sys/socket.h> |
监听连接 |
accept() |
<sys/socket.h> |
接受连接 |
示例:使用 open() 和 write() 创建文件
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h>
int main() {
int fd = open("test.txt", O_CREAT | O_WRONLY, 0644);
if (fd == -1) {
perror("open failed");
return 1;
}
const char msg = "Hello, Linux!n";
write(fd, msg, 13);
close(fd);
return 0;
}
常用库函数分类
- 文件操作:
fopen(),fclose(),fread(),fwrite() - 进程管理:
system(),popen(),getpid(),getppid() - 内存管理:
malloc(),free(),calloc() -
字符串处理:
strcpy(),strlen(),strcmp() - 时间日期:
time(),localtime(),strftime()
如何查看 Linux 函数帮助?
查看 Shell 函数帮助
help function_name # 查看内置命令或函数帮助man bash # 查看 Bash 手册,搜索 Functions
查看 C 库函数帮助(man 手册)
man open # 查看 open 系统调用man 2 open # 查看系统调用(第2类手册)man 3 printf # 查看 C 库函数(第3类手册)
提示:
man 2是系统调用,man 3是 C 库函数,很多函数名相同,但实现不同(如open是系统调用,fopen是库函数)。
| 类型 | 适用场景 | 关键特性 |
|---|---|---|
| Shell 函数 | 自动化脚本、运维工具 | 易用、参数通过 $1 传递、返回状态码或 echo 输出 |
| C 系统调用/库函数 | 系统编程、高性能应用 | 与内核交互、严格类型、错误处理通过返回值和 errno |
如果你有具体的函数想了解(如 fork()、grep、awk 中的函数等),欢迎提供更详细的需求,我可以为你深入解析!
首发原创文章,作者:世雄 - 原生数据库架构专家,如若转载,请注明出处:https://idctop.com/article/486734.html



