根据要求完成父进程与子进程之间通信。(Linux进程间通讯实践)

父子进程间通讯

​ 根据要求完成父进程与子进程之间通信。 父进程定时、随机产生一个由 \(12\) 个字符组成的字符串,子进程获取此字符 串后将字符串反转后输出并通知父进程。要求程序在运行过程种屏蔽 “\(Ctrl+C\)”,仅当程序接收到键盘输入“ \(q\) ”或“ \(Q\)": 时退出。

需要link pthread库!, eg. #gcc a.cpp -lpthread -o a

思路

​ 利用 \(pipe()\) 建立两个管道,分别用来父向子通信和子向父通信。

​ 屏蔽 \(Ctrl+C\) 只需要屏蔽掉对应信号即可,利用 \(signal()\) 函数屏蔽对应信号即可。

​ 开一个新线程循环检测键盘输入,关掉输入缓冲区以及回显。来保证按下键即可有反应。同时由于 \(getchar()\) 的存在,需要不断刷新输出缓冲区,来保证可以正常输出。

代码部分

#include<stdio.h>
#include<signal.h>
#include<unistd.h>
#include<sys/types.h>
#include<time.h>
#include<stdlib.h>
#include<pthread.h>
void swap(char* a,char* b){
    char tp=*a;
    *a=*b;*b=tp;
    return;
}
void *thread(void *arg){
    char c;
    while(c=getchar()){
        if(c=='Q'||c=='q'){
            system("stty echo");
            exit(0);
        }
    }
    return NULL;
}
int main(){
    signal(SIGINT,SIG_IGN);
    pthread_t t_id;
    system("stty -icanon -echo");
    pthread_create(&t_id,NULL,thread,NULL);
    int fd1[2];
    int fd2[2];
    int i;
    char messageRecive[20],messageSent[20];
    for(i=0;i<20;i++){
        messageRecive[i]=messageSent[i]=0;
    }
    messageSent[12]=0;
    int pid=-1;
    pipe(fd1);
    pipe(fd2);
    pid=fork();
    if(pid!=0){
        close(fd1[0]);close(fd2[1]);
        while(1){
            for(i=0;i<12;i++){
                messageSent[i]='a'+rand()%26;
            }
            printf("Father send:%s\n",messageSent);
            fflush(stdout);
            write(fd1[1],messageSent,12);
            read(fd2[0],messageRecive,15);
            printf("Father recive:%s\n",messageRecive);
            fflush(stdout);
            sleep(2);
        }
    }else{
        close(fd1[1]);close(fd2[0]);
        while(1){
            read(fd1[0],messageRecive,12);
            messageRecive[12]=0;
            printf("Child recive:%s\n",messageRecive);
            fflush(stdout);
            for(i=0;i<6;i++){
                swap(&messageRecive[i],&messageRecive[11-i]);
            }
            printf("Child reverse:%s\n",messageRecive);
            fflush(stdout);
            write(fd2[1],"Reverse OK",10);
        }
    }
    return 0;
}
posted @ 2020-11-18 23:09  萧瑟秋风今又是又是今  阅读(619)  评论(1编辑  收藏  举报