Linux 系统调用:实用示例143


系统调用是操作系统提供的接口,允许用户模式程序与内核交互。在 Linux 系统中,系统调用通过称为 syscalls 的特殊指令进行。这些指令以数字标识符表示,并通过 int 0x80 中断向内核发送。

读取系统时间

clock_gettime 系统调用获取系统时间。它需要两个参数:时钟 ID 和一个结构来存储返回的时间值。以下代码示例演示如何读取系统时间:```c
#include
#include
int main() {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, &ts);
printf("Current time: %ld.%09ld", ts.tv_sec, ts.tv_nsec);
return 0;
}
```

打开文件

open 系统调用打开一个文件。它需要三个参数:要打开的文件路径、打开模式和文件权限。以下代码示例演示如何打开一个文件进行读取:```c
#include
#include
int main() {
int fd = open("", O_RDONLY);
if (fd == -1) {
perror("open() failed");
return 1;
}
// 操作已打开的文件
close(fd);
return 0;
}
```

读取文件

read 系统调用从打开的文件中读取数据。它需要三个参数:文件描述符、缓冲区和读取的字节数。以下代码示例演示如何从文件中读取数据:```c
#include
int main() {
int fd = open("", O_RDONLY);
if (fd == -1) {
perror("open() failed");
return 1;
}
char buffer[1024];
ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
if (bytes_read == -1) {
perror("read() failed");
close(fd);
return 1;
}
// 处理已读数据
close(fd);
return 0;
}
```

写入文件

write 系统调用向打开的文件中写入数据。它需要三个参数:文件描述符、缓冲区和写入的字节数。以下代码示例演示如何向文件中写入数据:```c
#include
int main() {
int fd = open("", O_WRONLY | O_TRUNC);
if (fd == -1) {
perror("open() failed");
return 1;
}
const char *data = "Hello, world!";
ssize_t bytes_written = write(fd, data, strlen(data));
if (bytes_written == -1) {
perror("write() failed");
close(fd);
return 1;
}
close(fd);
return 0;
}
```

创建新进程

fork 系统调用创建一个新进程。它不会在当前进程中创建新线程,而是创建一个与当前进程完全相同的子进程,拥有自己的内存空间和执行流。以下代码示例演示如何创建新进程:```c
#include
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("fork() failed");
return 1;
}
if (pid == 0) {
// 子进程执行的代码
} else {
// 父进程执行的代码
}
return 0;
}
```

等待子进程

wait 系统调用等待子进程终止。它需要一个参数:指向子进程 PID 的指针。以下代码示例演示如何等待子进程:```c
#include
#include
int main() {
pid_t pid = fork();
if (pid == -1) {
perror("fork() failed");
return 1;
}
if (pid == 0) {
// 子进程执行的代码
exit(0);
}
int status;
wait(&status);
if (WIFEXITED(status)) {
printf("子进程退出状态:%d", WEXITSTATUS(status));
}
return 0;
}
```

系统调用是 Linux 系统编程的关键方面。它们提供了与内核交互并执行各种操作的方法,例如读取文件、创建新进程和管理内存。了解和正确使用系统调用对于编写强大的和高效的 Linux 程序至关重要。

2024-11-09


上一篇:Linux 系统彻底卸载 Oracle

下一篇:华为鸿蒙系统:蓝色屏的探索