5.13 作业+思维导图

 

#define _GNU_SOURCE                    //启用特性,使MSG_EXCEPT宏生效

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>   
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdbool.h>
#include <sys/msg.h>
#include <signal.h>

int msgflg = IPC_NOWAIT;                //切换状态时不会阻塞在msgrcv,而是立刻切换

struct st_msg{
    long mtype;
    char mtext[128];
};

void sig_handler(int signum){
    static bool flag = true;
    switch(signum){
        case SIGINT:                                                             
            if(flag){
                msgflg |= MSG_EXCEPT;
                flag = false;
            }
            else{
                msgflg &= ~MSG_EXCEPT;
                flag = true;
            }
            break;
        case SIGQUIT:                  //Ctrl+\用于关闭程序
            puts("quit");
            exit(EXIT_SUCCESS);        //退出整个进程
            break;
        default:
            break;
    }
}



void getLine(char* buf){
    char ret, i = 0;
    while((ret = fgetc(stdin)) != EOF && ret != '\n')
        buf[i++] = ret;
}

void* task(void* args){
    int *arg = args;
    struct st_msg r_msg = { .mtype = arg[1] };
    while(1){
        memset(r_msg.mtext, 0, sizeof(r_msg.mtext));
        int retval = msgrcv(arg[0], &r_msg, sizeof(r_msg.mtext), arg[1], msgflg);
        if(retval != -1 && retval != 0)    //有消息才打印到终端
            puts(r_msg.mtext);
    }
}

int main(int argc, const char *argv[])
{
    if(argc != 3){
        puts("Invalid number of arguments");
        return 1;
    }
    puts("Ctrl+\\ to quit");
    int r_msgtype = atoi(argv[1]);        //读的消息类型为argv[1]
    printf("msgtype %d for read\n", r_msgtype);
    int w_msgtype = atoi(argv[2]);        //写的消息类型为argv[2]
    printf("msgtype %d for write\n", w_msgtype);
    if(access("./ipckey", F_OK))
        system("touch ipckey");
    key_t key = ftok("./ipckey", 1);
    if(-1 == key){
        perror("ftok");
        return 1;
    }
    int msgid = msgget(key, IPC_CREAT|0666);
    if(-1 == msgid){
        perror("msgget");
        return 1;
    }
    pthread_t pid;
    int arg[2] = {msgid, r_msgtype};    //用于给线程传参
    pthread_create(&pid, NULL, task, arg);
    pthread_detach(pid);

    signal(SIGINT, sig_handler);        //注册信号及处理函数
    signal(SIGQUIT, sig_handler);
    struct st_msg msg = { .mtype = w_msgtype };
    while(1){
        memset(msg.mtext, 0, sizeof(msg.mtext));
        getLine(msg.mtext);
        msgsnd(msgid, &msg, strlen(msg.mtext), 0);
    }
    return 0;
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值