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


posted @ 2007-06-30 16:58  曹立松  阅读(456)  评论(0编辑  收藏  举报