linux下的管道通信程序

client.c功能:向管道发送数据

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/select.h>
#include <sys/time.h>
#define SIP_PIPE    "/tmp/sip-reg"
#define MSG_SIZE    100
int main(void)
{
    int sip_writer_fd;
    static char buffer[MSG_SIZE];
    int test = 1000;
    sip_writer_fd = open(SIP_PIPE, O_WRONLY | O_NONBLOCK);
    if (sip_writer_fd < 0) {
        perror("open control pipe for write");
        exit(1);
    }

    for (;;)
    {
        memset(buffer, 0, sizeof buffer);
        sprintf(buffer,"%d/n",test++);
        write(sip_writer_fd, buffer, strlen(buffer));
        sleep(1);
    }
    return 0;

server.c功能:从管道读取并打印到终端

int main(void)
{
    int sip_control_pipe;
    static char buffer[MSG_SIZE];
    double period = 0.5;
    unlink(SIP_PIPE);
    mkfifo(SIP_PIPE, 0666);

    sip_control_pipe = open(SIP_PIPE, O_RDONLY | O_NONBLOCK);
    if (sip_control_pipe < 0)
    {
        perror("open control pipe for read");
        exit(1);
    }
    for (;;)
    {
        fd_set rds;
        struct timeval step;
        int ret,len;

        FD_ZERO(&rds);
        FD_SET(sip_control_pipe, &rds);
        step.tv_sec  = period;
        step.tv_usec = (period - step.tv_sec) * 1000000L;

        ret = select(sip_control_pipe + 1, &rds, NULL, NULL, &step);
        if (ret < 0) {
            perror("select");
            exit(1);
        }
        if ((ret != 0) && (FD_ISSET(sip_control_pipe, &rds)))
        {
            memset(buffer, 0, sizeof buffer);
            len = read(sip_control_pipe, buffer, MSG_SIZE);
            if (len < MSG_SIZE)
            {
                printf(buffer);
            }
        }
    }
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值