8.29作业

send.c

#include <myhead.h>
struct msgbuf {
    long mytype;
    char mtext[1000];
};
int main() 
{
    key_t key = ftok("./", 65);
    struct msgbuf message;
	if(key==-1)
	{
		perror("ftok");
		return -1;
	}
    int msgID = msgget(key, 0666 | IPC_CREAT);
    if(msgID == -1) 
	{
        perror("msgget");
        exit(1);
    }
    pid_t pid = fork();
    if (pid < 0) 
	{
        perror("fork");
        exit(1);
    } 
	else if (pid == 0) 
	{
        printf("子进程启动,等待父进程发送消息...\n");
        exit(0);
    } 
	else 
	{
        printf("父进程启动,开始发送消息...\n");
        while(1) 
		{
            printf("输入消息 (输入'exit'退出): ");
            fgets(message.mtext, 1000, stdin);
            message.mtext[strcspn(message.mtext, "\n")] = 0; // 移除换行符
            message.mytype = 1;
            if (msgsnd(msgID, &message, sizeof(message.mtext), 0) == -1) {
                perror("msgsnd");
                exit(1);
            }
            if (strcmp(message.mtext, "exit") == 0) {
                break;
            }
        }
        wait(NULL);
        printf("父进程结束\n");
    }
    return 0;
}

rev.c

#include <myhead.h>
struct msgbuf {
    long mytype;
    char mtext[1000];
};
int main() 
{
    key_t key = ftok("./", 65);
    struct msgbuf message;
	if(key==-1)
	{
		perror("ftok");
		return -1;
	}
    int msgID = msgget(key, 0666 | IPC_CREAT);
    if(msgID == -1) 
	{
        perror("msgget");
        exit(1);
    }
    pid_t pid = fork();
    if (pid < 0) 
	{
        perror("fork");
        exit(1);
    } 
	else if (pid == 0) 
	{
        printf("子进程启动,开始接收消息...\n");
        while(1) {
            if (msgrcv(msgID, &message, sizeof(message.mtext), 1, 0) == -1) {
                perror("msgrcv");
                exit(1);
            }
            printf("收到消息: %s\n", message.mtext);
            if (strcmp(message.mtext, "exit") == 0) {
                break;
            }
        }
        printf("子进程结束\n");
        exit(0);    } 
	else 
	{
        printf("父进程启动,等待子进程接收消息...\n");
        wait(NULL);
        if (msgctl(msgID, IPC_RMID, NULL) == -1) {
            perror("msgctl");
            exit(1);
        }
        printf("父进程结束,消息队列已删除\n");
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值