import pika
def send_message():
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明一个队列
channel.queue_declare(queue='hello')
# 发送消息
channel.basic_publish(exchange='',
routing_key='hello',
body='Hello World!')
print(" [x] Sent 'Hello World!'")
# 关闭连接
connection.close()
if __name__ == '__main__':
send_message()
import pika
def receive_message():
connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()
# 声明一个队列
channel.queue_declare(queue='hello')
# 定义回调函数来处理接收到的消息
def callback(ch, method, properties, body):
print(" [x] Received %r" % body)
# 设置消息接收的回调函数
channel.basic_consume(queue='hello',
on_message_callback=callback,
auto_ack=True)
print(' [*] Waiting for messages. To exit press CTRL+C')
channel.start_consuming()
if __name__ == '__main__':
receive_message()
2.
from multiprocessing import Process, Value, Array
def sender(shared_value, shared_array):
# 将共享内存中的值设置为100
shared_value.value = 100
# 将共享内存数组的前5个元素设置为[1, 2, 3, 4, 5]
for i in range(5):
shared_array[i] = i + 1
print("Sender has set the value to 100 and the array to [1, 2, 3, 4, 5]")
if __name__ == '__main__':
# 创建一个共享的Value,初始值为0
shared_value = Value('i', 0)
# 创建一个共享的Array,大小为10,初始值为0
shared_array = Array('i', [0] * 10)
# 创建并启动发送进程
sender_process = Process(target=sender, args=(shared_value, shared_array))
sender_process.start()
sender_process.join()
# 打印接收到的数据
print("Received value:", shared_value.value)
print("Received array:", list(shared_array))
3.
父进程代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <string.h>
// 消息结构体
struct message {
long mtype;
char mtext[80];
};
int main() {
key_t key = ftok("somefile", 'a'); // 创建唯一的键
if (key == -1) {
perror("ftok");
exit(1);
}
int msgid = msgget(key, 0666 | IPC_CREAT); // 获取消息队列
if (msgid == -1) {
perror("msgget");
exit(1);
}
// 创建消息
struct message msg;
msg.mtype = 1;
strcpy(msg.mtext, "Hello from parent!");
// 发送消息
if (msgsnd(msgid, &msg, sizeof(msg.mtext), 0) == -1) {
perror("msgsnd");
exit(1);
}
printf("Message sent by parent.\n");
// 销毁消息队列
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}
子进程代码
#include <stdio.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <unistd.h>
// 消息结构体
struct message {
long mtype;
char mtext[80];
};
int main() {
key_t key = ftok("somefile", 'a'); // 使用与父进程相同的键
int msgid = msgget(key, 0666);
if (msgid == -1) {
perror("msgget");
exit(1);
}
// 接收消息
struct message rcv_msg;
while (msgrcv(msgid, &rcv_msg, sizeof(rcv_msg.mtext), rcv_msg.mtype, 0) == -1) {
perror("msgrcv");
}
printf("Message received by child: %s\n", rcv_msg.mtext);
// 销毁消息队列
if (msgctl(msgid, IPC_RMID, NULL) == -1) {
perror("msgctl");
exit(1);
}
return 0;
}