用有名管道实现两人的通信

一. 代码段:

        ① :头文件

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <string.h。
#include <unistd.h>

        ② 代码段:

#define FIFO_PATH "/tmp/my_fifo"
#define MSG_LENGTH  20

int Fifo_Spreak_Init();                      //通信初始化 
int Fifo_Spreakint(int fifo_fd);             //进行通信
int Fifo_Spreak_Free();                      //通信释放

int Fifo_Spreak_Init()                        // 初始化函数
{        
    if(access(FIFO_PATH,F_OK))
    {
        umask(0000);
        mkfifo(FIFO_PATH,0777);              // 不存在则创建管道
    }

    int fifo_fd = open(FIFO_PATH,O_RDWR);    // 用open打开管道
    if(fifo_fd == -1)
    {
        perror("open");
        return -1;
    }

    return fifo_fd;                           //  返回fifo_fd
}

int Fifo_Spreakint(int fifo_fd)               //进行通信
{
    int pid = fork();                         // 创建父子进程,分别执行读和写的操作
    char msg_data[MSG_LENGTH];
    if(pid == -1)
    {
        perror("fork");
        return -1;
    }
    else if(pid == 0)                          // 子进程:用来执行读
    {
        

        while(1)
        {
            memset(msg_data,0,MSG_LENGTH);
            read(fifo_fd,msg_data,MSG_LENGTH);
            printf("小明说:%s\n",msg_data);
        }
       
    }
    else                                       // 父进程用来执行发送信息
    {
        while(1)
        {
            memset(msg_data,0,MSG_LENGTH);
            printf("请输入要发送给小明的信息:");
            scanf("%s",msg_data);
            kill(pid,SIGSTOP);//system("kill -19 ");//用kill,发送给子进程信息,使子进程暂停
            sleep(1);
            write(fifo_fd,msg_data,strlen(msg_data));
            sleep(1);
            kill(pid,SIGCONT);
            printf("唤醒子进程!\n");
        }
       
    }
    return 0;
}

int Fifo_Spreak_Free(int fifo_fd)        //通信释放
{
    close(fifo_fd);

    return 0;
}

int main()
{
    int fifo_fd = Fifo_Spreak_Init();
    if(fifo_fd == -1)
    {
        printf("管道通初始化失败\n");
        return -1;
    }

    Fifo_Spreakint(fifo_fd);             //进行通信

    Fifo_Spreak_Free(fifo_fd);

    return 0;
}

        ③ :另外创建一个文件和此文件代码相同,然后gcc编译,运行

二、具体实现效果

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值