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;
}

發佈了18 篇原創文章 · 獲贊 1 · 訪問量 6萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章