在Linux上,C++可以通過多種方式實現進程間通信(IPC)。以下是一些常用的IPC方法:
pipe()系統調用創建一個管道,然后使用read()和write()系統調用進行讀寫操作。#include <iostream>
#include <unistd.h>
#include <fcntl.h>
int main() {
int pipefd[2];
char buffer[10];
if (pipe(pipefd) == -1) {
perror("pipe");
return 1;
}
pid_t pid = fork();
if (pid == 0) { // 子進程
close(pipefd[1]); // 關閉寫端
read(pipefd[0], buffer, sizeof(buffer));
std::cout << "子進程收到消息: " << 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]);
}
return 0;
}
#include <iostream>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
const char* fifo_name = "my_fifo";
mkfifo(fifo_name, 0666);
int fd = open(fifo_name, O_RDWR);
if (fd == -1) {
perror("open");
return 1;
}
const char* message = "Hello from named pipe!";
write(fd, message, strlen(message) + 1);
char buffer[10];
read(fd, buffer, sizeof(buffer));
std::cout << "收到消息: " << buffer << std::endl;
close(fd);
unlink(fifo_name);
return 0;
}
msgget()、msgsnd()和msgrcv()系統調用操作消息隊列。#include <iostream>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msg_buffer {
long msg_type;
char msg_text[100];
};
int main() {
key_t key = ftok("msgqueue_example.c", 'a');
int msgid = msgget(key, 0666 | IPC_CREAT);
msg_buffer message;
message.msg_type = 1;
strcpy(message.msg_text, "Hello from message queue!");
msgsnd(msgid, &message, sizeof(message.msg_text), 0);
msgrcv(msgid, &message, sizeof(message.msg_text), 1, 0);
std::cout << "收到消息: " << message.msg_text << std::endl;
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
shmget()、shmat()和shmdt()系統調用操作共享內存。#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
int main() {
key_t key = ftok("shared_memory_example.c", 'a');
int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
char* shared_memory = (char*)shmat(shmid, NULL, 0);
if (shared_memory == (char*)-1) {
perror("shmat");
return 1;
}
strcpy(shared_memory, "Hello from shared memory!");
sleep(2); // 等待其他進程讀取數據
std::cout << "從共享內存讀取數據: " << shared_memory << std::endl;
shmdt(shared_memory);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
kill()系統調用發送信號,使用signal()或sigaction()系統調用處理信號。#include <iostream>
#include <csignal>
#include <unistd.h>
void signal_handler(int signal) {
std::cout << "收到信號: " << signal << std::endl;
}
int main() {
signal(SIGUSR1, signal_handler);
std::cout << "進程ID: " << getpid() << std::endl;
sleep(5); // 等待其他進程發送信號
return 0;
}
socket()、bind()、listen()、accept()、connect()和send()/recv()系統調用進行套接字通信。這些只是Linux上C++進程間通信的一些方法。根據具體需求和場景,可以選擇合適的IPC機制。