在 Linux 下使用 C++ 进行系统调用,通常需要包含适当的头文件,并使用特定的函数调用系统提供的功能。以下是一些基本步骤和示例:
大多数系统调用需要包含 <unistd.h>、<sys/syscall.h>、<fcntl.h> 等头文件。具体的头文件取决于你要使用的系统调用。
系统调用通常以 syscall 函数的形式进行封装,但许多常用的系统调用也有直接的 C/C++ 函数接口。
下面是一些常见的系统调用示例:
fork() 系统调用#include <iostream>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == -1) {
std::cerr << "Fork failed" << std::endl;
return 1;
} else if (pid == 0) {
// 子进程
std::cout << "Child process, PID: " << getpid() << std::endl;
} else {
// 父进程
std::cout << "Parent process, PID: " << getpid() << ", Child PID: " << pid << std::endl;
}
return 0;
}
exec() 系列系统调用#include <iostream>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
// 子进程
char *args[] = {"/bin/ls", "-l", NULL};
execvp(args[0], args);
std::cerr << "Exec failed" << std::endl;
return 1;
} else if (pid > 0) {
// 父进程
int status;
waitpid(pid, &status, 0);
} else {
std::cerr << "Fork failed" << std::endl;
}
return 0;
}
read() 和 write() 系统调用#include <iostream>
#include <unistd.h>
#include <fcntl.h>
int main() {
int fd = open("example.txt", O_RDONLY);
if (fd == -1) {
std::cerr << "Open file failed" << std::endl;
return 1;
}
char buffer[10];
ssize_t bytesRead = read(fd, buffer, sizeof(buffer) - 1);
if (bytesRead == -1) {
std::cerr << "Read failed" << std::endl;
close(fd);
return 1;
}
buffer[bytesRead] = '\0'; // Null-terminate the string
std::cout << "Read from file: " << buffer << std::endl;
close(fd);
return 0;
}
syscall() 函数对于一些不直接提供 C/C++ 接口的系统调用,可以使用 syscall() 函数。
#include <iostream>
#include <unistd.h>
#include <sys/syscall.h>
int main() {
long result = syscall(SYS_getpid);
std::cout << "PID: " << result << std::endl;
return 0;
}
这些示例展示了如何在 Linux 下使用 C++ 进行基本的系统调用。根据需要,你可以查阅 Linux 手册页(man 命令)来获取更多系统调用的详细信息和使用方法。