在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;
}
mkfifo()
系统调用创建一个命名管道,然后使用open()
、read()
和write()
函数进行读写操作。#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");
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>
#include <cstring>
struct msg_buffer {
long msg_type;
char msg_text[100];
};
int main() {
key_t key = ftok("msgqueue_example", '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);
msg_buffer received_message;
msgrcv(msgid, &received_message, sizeof(received_message.msg_text), 1, 0);
std::cout << "收到消息: " << received_message.msg_text << std::endl;
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
shmget()
、shmat()
、shmdt()
和shmctl()
函数进行共享内存操作。#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>
int main() {
key_t key = ftok("shared_memory_example", '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!");
std::cout << "共享内存中的消息: " << shared_memory << std::endl;
shmdt(shared_memory);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
signal()
或sigaction()
函数设置信号处理函数,然后使用kill()
函数发送信号。#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);
kill(getpid(), SIGUSR1);
return 0;
}
socket()
、bind()
、listen()
、accept()
、connect()
、send()
和recv()
等函数进行套接字操作。这些只是Linux中C++进程间通信的一些方法。在实际应用中,可以根据需求选择合适的IPC机制。