在Linux中,C++可以通过多种方式实现进程间通信(IPC)。以下是一些常见的IPC方法:
pipe()
系统调用创建一个管道,然后使用read()
和write()
系统调用进行读写操作。#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) { // Parent process
close(pipefd[0]); // Close unused read end
const char *msg = "Hello from parent!";
write(pipefd[1], msg, strlen(msg) + 1);
close(pipefd[1]);
wait(NULL); // Wait for child process to finish
} else { // Child process
close(pipefd[1]); // Close unused write end
read(pipefd[0], buffer, sizeof(buffer));
std::cout << "Child received: " << buffer << std::endl;
close(pipefd[0]);
}
return 0;
}
mkfifo()
系统调用创建一个命名管道,然后像使用普通文件一样进行读写操作。#include <iostream>
#include <fcntl.h>
#include <sys/stat.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");
exit(EXIT_FAILURE);
}
const char *msg = "Hello from FIFO!";
write(fd, msg, strlen(msg) + 1);
char buffer[10];
read(fd, buffer, sizeof(buffer));
std::cout << "Received: " << buffer << std::endl;
close(fd);
unlink(fifo_name);
return 0;
}
msgget()
、msgsnd()
和msgrcv()
系统调用实现消息队列通信。#include <iostream>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <cstring>
struct msg_buffer {
long msg_type;
char msg_text[100];
};
int main() {
key_t key = ftok("msgqueue_example", 65);
int msgid = msgget(key, 0666 | IPC_CREAT);
msg_buffer buffer;
buffer.msg_type = 1;
strcpy(buffer.msg_text, "Hello from message queue!");
msgsnd(msgid, &buffer, sizeof(buffer.msg_text), 0);
msgrcv(msgid, &buffer, sizeof(buffer.msg_text), 1, 0);
std::cout << "Received: " << buffer.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 <cstring>
int main() {
key_t key = ftok("shared_memory_example", 65);
int shmid = shmget(key, 1024, 0666 | IPC_CREAT);
char *data = (char *)shmat(shmid, NULL, 0);
if (data == (char *)-1) {
perror("shmat");
exit(EXIT_FAILURE);
}
strcpy(data, "Hello from shared memory!");
std::cout << "Data: " << data << std::endl;
shmdt(data);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
signal()
或sigaction()
系统调用设置信号处理函数,然后使用kill()
系统调用发送信号。#include <iostream>
#include <csignal>
#include <unistd.h>
void signal_handler(int signal) {
std::cout << "Received signal: " << signal << std::endl;
}
int main() {
signal(SIGUSR1, signal_handler);
std::cout << "Waiting for signal..." << std::endl;
pause(); // Wait for a signal
return 0;
}
socket()
、bind()
、listen()
、accept()
、connect()
、send()
和recv()
等系统调用实现套接字通信。这些只是Linux中C++实现进程间通信的一些方法。具体选择哪种方法取决于您的需求和应用场景。