在操作系统中,进程间通信(IPC)是一种重要的机制,允许不同的进程之间进行数据交换和信息传递。本文将介绍几种常见的进程间通信方式,并提供用C语言实现的简单示例。
#include
#include
int main() {
int pipe_fd[2];
char buffer[30];
// 创建管道
if (pipe(pipe_fd) == -1) {
perror("pipe");
return 1;
}
// 创建子进程
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) { // 子进程
close(pipe_fd[1]); // 关闭写入端
// 从管道读取数据
read(pipe_fd[0], buffer, sizeof(buffer));
printf("Child Process: Received message from parent: %s\n", buffer);
close(pipe_fd[0]);
} else { // 父进程
close(pipe_fd[0]); // 关闭读取端
const char* message = "Hello from Parent Process!";
// 将数据写入管道
write(pipe_fd[1], message, strlen(message) + 1);
close(pipe_fd[1]);
}
return 0;
}
#include
#include
#include
#include
struct message {
long msg_type;
char msg_text[100];
};
int main() {
key_t key;
int msg_id;
// 创建唯一的键值
key = ftok("msg_queue_key", 65);
// 创建消息队列
msg_id = msgget(key, 0666 | IPC_CREAT);
struct message msg;
// 发送消息
msg.msg_type = 1;
strcpy(msg.msg_text, "Hello from Message Queue!");
msgsnd(msg_id, &msg, sizeof(msg), 0);
printf("Message Sent: %s\n", msg.msg_text);
return 0;
}
#include
#include
#include
int main() {
key_t key;
int shmid;
char* data;
// 创建唯一的键值
key = ftok("shared_memory_key", 65);
// 创建共享内存
shmid = shmget(key, 1024, 0666 | IPC_CREAT);
// 将共享内存连接到当前进程的地址空间
data = (char*)shmat(shmid, (void*)0, 0);
// 写入数据到共享内存
sprintf(data, "Hello from Shared Memory!");
printf("Data Written: %s\n", data);
// 分离共享内存
shmdt(data);
return 0;
}
#include
#include
#include
#include
#include
#define PORT 8080
int main() {
int server_fd, new_socket;
struct sockaddr_in address;
int addrlen = sizeof(address);
char buffer[1024] = {0};
const char* hello = "Hello from Socket!";
// 创建套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// 绑定套接字到地址和端口
if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 监听连接
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// 接受连接
if ((new_socket = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// 发送数据
send(new_socket, hello, strlen(hello), 0);
printf("Message Sent: %s\n", hello);
close(new_socket);
close(server_fd);
return 0;
}
#include
#include
#include
#include
void signal_handler(int signum) {
if (signum == SIGUSR1) {
printf("Received SIGUSR1 signal.\n");
}
}
int main() {
// 注册信号处理函数
signal(SIGUSR1, signal_handler);
// 发送信号给当前进程
kill(getpid(), SIGUSR1);
return 0;
}