日期:2014-05-16  浏览次数:20586 次

Linux 线程之间用管道通信,出了个比较2的问题,贴代码,大家瞧瞧啊

#include <string.h>
#include <sys/types.h>
#include <sys/poll.h>
#include <unistd.h>
#include<stdio.h>
#include<pthread.h>
#include <iostream>

using namespace std;

int fd[2]= {-1, -1};
typedef struct Message
{
    unsigned int command;
    char    ch;
}Msg;


bool isNotEmpty(int fdR)
{
    struct pollfd pfd;
    pfd.fd = fd[0];
    pfd.events = POLLIN;
    pfd.revents = 0;

    if(pfd.fd <0)
    {
        cout<<"read descriptor not initialized!"<<endl;
        return false;
    }

    if(-1 == poll(&pfd, 1, 1000))
    {
        cout<<"poll error"<<endl;
        return false;
    }

    if(pfd.revents & POLLIN)
    {
        return true;
    }

    return false;
}

void put(Msg *msg)
{
    if(fd[1] > 0)
    {
       int err = write(fd[1], (char*)msg, sizeof(*msg));
       printf("wirte message :%d\n", msg->command);
       printf("wirte message :%c\n", msg->ch);

       if(err < 0)
       {
           cout<<"write pipe failed!"<<endl;
       }
    }
    else
    {
        cout<< "read descriptor not initialized"<<endl;
    }
}

int get()
{
    char chstr[10];
    int len = 0;
    int err = read(fd[0], chstr, sizeof(chstr));
    if(err < 0)
    {
        cout<<"read pipe failed"<<endl;
    }

    len = strlen(chstr);
    chstr[len+1] = '\0';

    Msg *msg = (Msg*)chstr;
    printf("recevie message :%d\n", msg->command);
    printf("recevie message :%c\n", msg->ch);

    return msg->command;
}

void *recevieMsg(void *data)
{
    while(1)
    {
        if(isN