1.管道:
#include <stdio.h>
#include <unistd.h>
int main() {
int pipe_fd[2];
char message[] = "Hello, IPC!";
if (pipe(pipe_fd) == -1) {
perror("Pipe creation failed");
return 1;
}
pid_t child_pid = fork();
if (child_pid == -1) {
perror("Fork failed");
return 1;
}
if (child_pid == 0) {
close(pipe_fd[1]);
char buffer[100];
read(pipe_fd[0], buffer, sizeof(buffer));
printf("Child received: %s\n", buffer);
close(pipe_fd[0]);
} else {
close(pipe_fd[0]);
write(pipe_fd[1], message, sizeof(message));
close(pipe_fd[1]);
}
return 0;
}
2.共享内存:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/shm.h>
int main() {
key_t key = ftok("shm_example", 65);
int shmid = shmget(key, 1024, 0666|IPC_CREAT);
char *shared_memory = (char*) shmat(shmid, (void*)0, 0);
pid_t child_pid = fork();
if (child_pid == -1) {
perror("Fork failed");
return 1;
}
if (child_pid == 0) {
printf("Child received: %s\n", shared_memory);
} else {
sprintf(shared_memory, "Hello, IPC!");
wait(NULL);
shmdt(shared_memory);
shmctl(shmid, IPC_RMID, NULL);
}
return 0;
}
3.消息队列:
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msg_buffer {
long msg_type;
char msg_text[100];
};
int main() {
key_t key = ftok("msgq_example", 65);
int msgid = msgget(key, 0666|IPC_CREAT);
struct msg_buffer message;
pid_t child_pid = fork();
if (child_pid == -1) {
perror("Fork failed");
return 1;
}
if (child_pid == 0) {
msgrcv(msgid, &message, sizeof(message), 1, 0);
printf("Child received: %s\n", message.msg_text);
} else {
message.msg_type = 1;
sprintf(message.msg_text, "Hello, IPC!");
msgsnd(msgid, &message, sizeof(message), 0);
}
return 0;
}