关闭

linux下的管道通信程序

450人阅读 评论(0) 收藏 举报
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

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:185558次
    • 积分:3394
    • 等级:
    • 排名:第10231名
    • 原创:146篇
    • 转载:0篇
    • 译文:0篇
    • 评论:25条
    文章分类