在Linux下,C++可以通过多种方式实现进程间通信(IPC)。以下是一些常用的IPC方法:
#include <iostream>
#include <unistd.h>
int main() {
int pipefd[2];
pid_t pid;
char buffer[128];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid > 0) { // 父进程
close(pipefd[0]); // 关闭读端
const char *msg = "Hello from parent!";
write(pipefd[1], msg, strlen(msg) + 1);
close(pipefd[1]);
} else { // 子进程
close(pipefd[1]); // 关闭写端
read(pipefd[0], buffer, sizeof(buffer));
std::cout << "Message from child: " << buffer << std::endl;
close(pipefd[0]);
}
return 0;
}
#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 named pipe!";
write(fd, msg, strlen(msg) + 1);
char buffer[128];
read(fd, buffer, sizeof(buffer));
std::cout << "Message received: " << buffer << std::endl;
close(fd);
unlink(fifo_name);
return 0;
}
#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 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 << "Message received: " << buffer.msg_text << std::endl;
msgctl(msgid, IPC_RMID, NULL);
return 0;
}
#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 *data = (char *)shmat(shmid, NULL, 0);
if (data == (char *)-1) {
perror("shmat");
exit(EXIT_FAILURE);
}
strcpy(data, "Hello from shared memory!");
std::cout << "Message received: " << data << std::endl;
shmdt(data);
shmctl(shmid, IPC_RMID, NULL);
return 0;
}
#include <iostream>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/types.h>
union semun {
int val;
struct semid_ds *buf;
unsigned short *array;
};
int main() {
key_t key = ftok("semaphore_example", 'A');
int semid = semget(key, 1, 0666 | IPC_CREAT);
union semun arg;
arg.val = 1;
semctl(semid, 0, SETVAL, arg);
struct sembuf sb = {0, -1, SEM_UNDO};
semop(semid, &sb, 1);
std::cout << "Semaphore value: " << arg.val << std::endl;
arg.val = 0;
semctl(semid, 0, SETVAL, arg);
sb.sem_op = 1;
semop(semid, &sb, 1);
semctl(semid, 0, IPC_RMID, arg);
return 0;
}
这些IPC方法各有优缺点,可以根据实际需求选择合适的方法进行进程间通信。