在 Linux 下,C++ 可以通过多种方式来进行系统调用。以下是一些常用的方法:
许多系统调用在 C 标准库中都有对应的封装函数。例如:
fopen(), fclose(), read(), write(), stat() 等。fork(), exec(), wait(), exit() 等。signal(), sigaction() 等。#include <iostream>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
perror("open");
return 1;
}
char buffer[1024];
ssize_t bytes_read = read(fd, buffer, sizeof(buffer));
if (bytes_read == -1) {
perror("read");
close(fd);
return 1;
}
std::cout << "Read " << bytes_read << " bytes from file." << std::endl;
close(fd);
return 0;
}
syscall() 函数对于一些没有标准库封装的系统调用,可以直接使用 syscall() 函数。syscall() 函数接受一个系统调用号和相应的参数。
#include <iostream>
#include <unistd.h>
#include <sys/syscall.h>
#include <linux/unistd.h>
int main() {
long result = syscall(SYS_getpid);
std::cout << "PID: " << result << std::endl;
return 0;
}
在某些情况下,可能需要直接使用内联汇编来进行系统调用。这种方法比较底层,通常不推荐用于常规开发。
#include <iostream>
int main() {
long syscall_number = 42; // 示例系统调用号
long arg1 = 123;
long arg2 = 456;
long result;
asm volatile (
"mov $%1, %%rax\n\t"
"mov %2, %%rdi\n\t"
"mov %3, %%rsi\n\t"
"syscall\n\t"
"mov %%rax, %0\n\t"
: "=r" (result)
: "r" (syscall_number), "r" (arg1), "r" (arg2)
: "rax", "rdi", "rsi"
);
std::cout << "System call result: " << result << std::endl;
return 0;
}
如果需要进行多线程编程,可以使用 POSIX 线程库(pthread)来进行系统调用。
#include <iostream>
#include <pthread.h>
void* thread_function(void* arg) {
std::cout << "Thread running." << std::endl;
return nullptr;
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, nullptr, thread_function, nullptr);
if (result != 0) {
std::cerr << "Failed to create thread." << std::endl;
return 1;
}
pthread_join(thread, nullptr);
return 0;
}
syscall() 函数。选择合适的方法取决于具体的需求和场景。