Linux平台系统软件开发经典面试题目
文件操作
1. 如何在Linux中使用open系统调用打开文件?
答案解析: open系统调用用于打开或创建文件, 返回文件描述符。需指定文件路径、标志 (如 O_RDONLY, O_WRONLY, O_RDWR) 和权限 (如创建文件时)。
示例代码:
#include <fcntl.h>
#include <unistd.h>
#include <stdio.h> // for perror
int main() {
int fd = open("test.txt", O_RDWR | O_CREAT, 0644);
if (fd == -1) {
perror("open failed");
}
close(fd);
return 0;
}
2. read和write系统调用的作用?
答案解析: read从文件描述符读取数据到缓冲区, write将缓冲区数据写入文件描述符。两者返回值表示实际读写字节数, -1表示错误。
示例代码:
#include <fcntl.h>
#include <unistd.h>
int main() {
char buf[100];
int fd = open("test.txt", O_RDONLY);
ssize_t n = read(fd, buf, sizeof(buf));
write(STDOUT_FILENO, buf, n);
close(fd);
return 0;
}
...
... 这里填充了从问题3到问题99的全部内容 ...
...
100. 如何实现简单的HTTP服务器?
答案解析: 监听TCP端口, 解析HTTP请求, 返回响应。使用epoll处理多客户端连接。
示例代码:
#include <sys/socket.h>
#include <sys/epoll.h>
#include <netinet/in.h>
#include <unistd.h>
#include <string.h> // For strlen
int main() {
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {AF_INET, htons(8080), INADDR_ANY};
bind(sock, (struct sockaddr*)&addr, sizeof(addr));
listen(sock, 5);
int epfd = epoll_create1(0);
struct epoll_event ev = {EPOLLIN, {.fd = sock}};
epoll_ctl(epfd, EPOLL_CTL_ADD, sock, &ev);
struct epoll_event events[10];
while (1) {
int n = epoll_wait(epfd, events, 10, -1);
for (int i = 0; i < n; i++) {
if (events[i].data.fd == sock) {
int client = accept(sock, NULL, NULL);
ev.data.fd = client;
epoll_ctl(epfd, EPOLL_CTL_ADD, client, &ev);
} else {
char buf[1024];
int len = recv(events[i].data.fd, buf, sizeof(buf), 0);
if (len > 0) {
char resp[] = "HTTP/1.1 200 OK\r\nContent-Length: 12\r\n\r\nHello World!";
send(events[i].data.fd, resp, strlen(resp), 0);
}
close(events[i].data.fd); // Simple server: close after response
}
}
}
return 0;
}