在 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()
函數。選擇合適的方法取決于具體的需求和場景。