Linux系统编程是指在Linux操作系统环境下,利用系统调用和库函数直接与操作系统内核交互的编程方式。C++作为Linux系统编程的主要语言之一,能够充分发挥Linux系统的强大功能。
#include <fcntl.h>
#include <unistd.h>
// 低级文件操作示例
int fd = open("file.txt", O_RDWR | O_CREAT, 0644);
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);
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
// 进程创建示例
pid_t pid = fork();
if (pid == -1) {
perror("fork failed");
return -1;
} else if (pid == 0) {
// 子进程代码
execlp("/bin/ls", "ls", "-l", NULL);
perror("execlp failed");
_exit(1);
} else {
// 父进程代码
int status;
waitpid(pid, &status, 0);
if (WIFEXITED(status)) {
printf("Child exited with status %d\n", WEXITSTATUS(status));
}
}
#include <pthread.h>
void* thread_function(void* arg) {
// 线程执行的代码
return nullptr;
}
// 创建线程示例
pthread_t thread_id;
int ret = pthread_create(&thread_id, NULL, thread_function, NULL);
if (ret != 0) {
perror("pthread_create failed");
return -1;
}
pthread_join(thread_id, NULL);
int pipefd[2];
if (pipe(pipefd) == -1) {
perror("pipe failed");
return -1;
}
#include <sys/ipc.h>
#include <sys/shm.h>
int shmid = shmget(IPC_PRIVATE, size, IPC_CREAT | 0666);
if (shmid == -1) {
perror("shmget failed");
return -1;
}
void* shmaddr = shmat(shmid, NULL, 0);
if (shmaddr == (void*)-1) {
perror("shmat failed");
return -1;
}
#include <signal.h>
void signal_handler(int sig) {
// 处理信号
}
// 设置信号处理函数
struct sigaction sa;
sa.sa_handler = signal_handler;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if (sigaction(SIGINT, &sa, NULL) == -1) {
perror("sigaction failed");
return -1;
}
Linux系统编程中,大多数系统调用在出错时会返回-1,并设置全局变量errno来指示错误类型。
#include <errno.h>
#include <string.h>
int fd = open("nonexistent.txt", O_RDONLY);
if (fd == -1) {
// 使用perror输出错误信息
perror("open failed");
// 或者使用strerror获取错误字符串
fprintf(stderr, "Error: %s\n", strerror(errno));
// 直接使用errno
if (errno == ENOENT) {
fprintf(stderr, "File does not exist\n");
}
}
#include <sys/select.h>
fd_set readfds;
FD_ZERO(&readfds);
FD_SET(fd1, &readfds);
FD_SET(fd2, &readfds);
int maxfd = (fd1 > fd2) ? fd1 : fd2;
int ret = select(maxfd + 1, &readfds, NULL, NULL, NULL);
if (ret == -1) {
perror("select failed");
return -1;
}
if (FD_ISSET(fd1, &readfds)) {
// fd1有数据可读
}
#include <aio.h>
struct aiocb aio = {0};
aio.aio_fildes = fd;
aio.aio_buf = buffer;
aio.aio_nbytes = sizeof(buffer);
aio.aio_offset = 0;
if (aio_read(&aio) == -1) {
perror("aio_read failed");
return -1;
}
// 检查操作是否完成
while (aio_error(&aio) == EINPROGRESS) {
// 等待...
}
if (aio_error(&aio) != 0) {
perror("aio_error");
return -1;
}
ssize_t bytes_read = aio_return(&aio);
掌握这些基础概念和技术后,您将能够开发高效、可靠的Linux系统级应用程序。