C++在Linux如何实现进程间通信
导读:在Linux中,C++可以通过多种方式实现进程间通信(IPC)。以下是一些常用的IPC机制: 管道(Pipes): 匿名管道(Anonymous Pipes): 通常用于父子进程之间的通信。 命名管道(Named Pipes, FIF...
在Linux中,C++可以通过多种方式实现进程间通信(IPC)。以下是一些常用的IPC机制:
-
管道(Pipes):
- 匿名管道(Anonymous Pipes): 通常用于父子进程之间的通信。
- 命名管道(Named Pipes, FIFOs): 允许无亲缘关系的进程之间进行通信。
-
信号(Signals):
- 用于通知接收进程某个事件已经发生。
-
消息队列(Message Queues):
- 允许进程发送和接收消息队列中的消息。
-
共享内存(Shared Memory):
- 允许多个进程访问同一块物理内存区域,是最快的IPC形式之一。
-
信号量(Semaphores):
- 用于进程同步,控制对共享资源的访问。
-
套接字(Sockets):
- 可用于不同机器之间的通信,也可以用于同一台机器上的进程间通信。
下面是一些简单的示例代码,展示了如何在C++中使用这些IPC机制:
匿名管道示例(父子进程通信)
#include <
iostream>
#include <
unistd.h>
#include <
sys/types.h>
#include <
sys/wait.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[10];
// 创建管道
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) {
// 子进程
close(pipefd[1]);
// 关闭写端
read(pipefd[0], buffer, sizeof(buffer));
// 读取消息
std::cout <
<
"Child received: " <
<
buffer <
<
std::endl;
close(pipefd[0]);
}
else {
// 父进程
close(pipefd[0]);
// 关闭读端
const char* message = "Hello from parent!";
write(pipefd[1], message, strlen(message) + 1);
// 发送消息
close(pipefd[1]);
wait(NULL);
// 等待子进程结束
}
return 0;
}
命名管道示例
#include <
iostream>
#include <
sys/stat.h>
#include <
fcntl.h>
#include <
unistd.h>
int main() {
const char* fifo = "/tmp/myfifo";
mkfifo(fifo, 0666);
int fd = open(fifo, O_WRONLY);
if (fd == -1) {
perror("open");
return 1;
}
const char* message = "Hello from FIFO!";
write(fd, message, strlen(message) + 1);
close(fd);
unlink(fifo);
// 删除命名管道
return 0;
}
共享内存示例
#include <
iostream>
#include <
sys/ipc.h>
#include <
sys/shm.h>
#include <
unistd.h>
int main() {
key_t key = ftok("shmfile", 65);
int shmid = shmget(key, 1024, 0666|IPC_CREAT);
char *str = (char*) shmat(shmid, (void*)0, 0);
strcpy(str, "Hello world!");
std::cout <
<
"String in shared memory: " <
<
str <
<
std::endl;
shmdt(str);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
信号量示例
#include <
iostream>
#include <
sys/ipc.h>
#include <
sys/sem.h>
#include <
unistd.h>
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
}
;
int main() {
key_t key = ftok("semfile", 65);
int semid = semget(key, 1, 0666|IPC_CREAT);
union semun arg;
arg.val = 1;
// 初始化信号量为1
semctl(semid, 0, SETVAL, arg);
// 使用信号量进行同步操作
// ...
semctl(semid, 0, IPC_RMID);
// 删除信号量集
return 0;
}
套接字示例(本地套接字)
// 服务器端
#include <
iostream>
#include <
sys/socket.h>
#include <
netinet/in.h>
#include <
unistd.h>
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
// 创建套接字文件描述符
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// 绑定套接字到端口
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(8080);
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &
opt, sizeof(opt))) {
perror("setsockopt");
exit(EXIT_FAILURE);
}
if (bind(server_fd, (struct sockaddr *)&
address, sizeof(address)) <
0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
if (listen(server_fd, 3) <
0) {
perror("listen");
exit(EXIT_FAILURE);
}
// 接受连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&
address, (socklen_t*)&
addrlen)) <
0) {
perror("accept");
exit(EXIT_FAILURE);
}
// 读取数据
char buffer[1024] = {
0}
;
read(new_socket, buffer, 1024);
std::cout <
<
"Message from client: " <
<
buffer <
<
std::endl;
// 发送响应
send(new_socket, "Hello from server", 17, 0);
std::cout <
<
"Hello message sent\n";
close(new_socket);
close(server_fd);
return 0;
}
// 客户端
#include <
iostream>
#include <
sys/socket.h>
#include <
arpa/inet.h>
#include <
unistd.h>
int main() {
int sock = 0;
struct sockaddr_in serv_addr;
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) <
0) {
std::cout <
<
"
Socket creation error
";
return -1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(8080);
// 将IPv4地址从文本转换为二进制形式
if(inet_pton(AF_INET, "127.0.0.1", &
serv_addr.sin_addr) <
= 0) {
std::cout <
<
"
Invalid address/ Address not supported
";
return -1;
}
if (connect(sock, (struct sockaddr *)&
serv_addr, sizeof(serv_addr)) <
0) {
std::cout <
<
"
Connection Failed
";
return -1;
}
send(sock, "Hello from client", 17, 0);
std::cout <
<
"Hello message sent\n";
char buffer[1024] = {
0}
;
read(sock, buffer, 1024);
std::cout <
<
"Message from server: " <
<
buffer <
<
std::endl;
close(sock);
return 0;
}
在使用这些IPC机制时,需要注意同步和互斥的问题,以避免竞态条件和数据不一致。此外,还需要考虑错误处理和资源的清理工作。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: C++在Linux如何实现进程间通信
本文地址: https://pptw.com/jishu/774006.html
