Linux系统资源回收代码
时间: 2024-04-06 22:09:31 浏览: 19
Linux系统中有多种资源需要回收,包括进程、内存、文件描述符等。下面是一些常见的回收资源的代码示例:
1. 回收进程资源
```c
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main() {
pid_t pid = fork();
if (pid < 0) {
fprintf(stderr, "Fork failed\n");
exit(1);
} else if (pid == 0) {
// Child process
printf("Child process, pid=%d\n", getpid());
exit(0);
} else {
// Parent process
printf("Parent process, pid=%d\n", getpid());
int status;
wait(&status); // 等待子进程结束
if (WIFEXITED(status)) {
printf("Child process exited with status %d\n", WEXITSTATUS(status));
} else if (WIFSIGNALED(status)) {
printf("Child process killed by signal %d\n", WTERMSIG(status));
}
}
return 0;
}
```
2. 回收内存资源
```c
#include <stdlib.h>
int main() {
// 申请内存
int *ptr = (int*)malloc(sizeof(int));
if (ptr == NULL) {
fprintf(stderr, "Memory allocation failed\n");
exit(1);
}
// 使用内存
*ptr = 123;
// 释放内存
free(ptr);
return 0;
}
```
3. 回收文件描述符资源
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("file.txt", O_RDONLY);
if (fd < 0) {
fprintf(stderr, "Failed to open file\n");
exit(1);
}
// 使用文件描述符
char buf[1024];
ssize_t nread = read(fd, buf, sizeof(buf));
if (nread < 0) {
fprintf(stderr, "Failed to read file\n");
exit(1);
}
// 关闭文件描述符
close(fd);
return 0;
}
```
相关推荐
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)