- 使用管道进行进程间通信:
#include <stdio.h>
#include <unistd.h>
int main() {
int pipe_fd[2];
char data[] = "Hello, Pipe!";
char buffer[20];
if (pipe(pipe_fd) == -1) {
perror("Pipe creation failed");
return 1;
}
if (fork() == 0) { // Child process
close(pipe_fd[0]); // Close the read end
write(pipe_fd[1], data, sizeof(data));
close(pipe_fd[1]);
} else { // Parent process
close(pipe_fd[1]); // Close the write end
read(pipe_fd[0], buffer, sizeof(buffer));
close(pipe_fd[0]);
printf("Received data: %s\n", buffer);
}
return 0;
}
- 使用共享内存进行进程间通信:
#include <stdio.h>
#include <unistd.h>
#include <sys/mman.h>
int main() {
size_t size = 4096; // Size of shared memory
char data[] = "Hello, Shared Memory!";
char *shared_memory;
int shm_fd = shm_open("/my_shared_memory", O_CREAT | O_RDWR, 0666);
ftruncate(shm_fd, size);
shared_memory = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
if (fork() == 0) { // Child process
sprintf(shared_memory, "%s", data);
} else { // Parent process
wait(NULL); // Wait for the child to finish writing
printf("Received data: %s\n", shared_memory);
shm_unlink("/my_shared_memory"); // Unlink shared memory
}
return 0;
}
- 使用消息队列进行进程间通信:
#include <stdio.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/msg.h>
struct msg_buffer {
long msg_type;
char msg_text[100];
};
int main() {
key_t key;
int msg_id;
struct msg_buffer message;
key = ftok("/tmp", 'a');
msg_id = msgget(key, 0666 | IPC_CREAT);
if (fork() == 0) { // Child process
message.msg_type = 1;
sprintf(message.msg_text, "Hello, Message Queue!");
msgsnd(msg_id, &message, sizeof(message), 0);
} else { // Parent process
wait(NULL); // Wait for the child to finish sending
msgrcv(msg_id, &message, sizeof(message), 1, 0);
printf("Received data: %s\n", message.msg_text);
msgctl(msg_id, IPC_RMID, NULL); // Remove message queue
}
return 0;
}