首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 操作系统 > UNIXLINUX >

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

2013-01-23 
Linux 线程之间用管道通信,出了个比较2的问题,贴代码,大家瞧瞧啊#include string.h#include sys/types.

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(isNotEmpty(fd[0]))
        {
            // 写线程,只写入了15个数据;


            if(get() == 14)
                break;
        }
        else
        {
            cout<<"pipe is empty!!!"<<endl;
        }
    }

}

void *sendMsg(void *data)
{
    Msg msg;
    // 向管道写入15个数据;
    for(int i=0; i<15; i++)
    {
        msg.command = i;
        msg.ch = 'a' + i;

        put(&msg);
        //usleep(10);
    }
}

int main()
{
    void *retval;
    pthread_t pth_a, pth_b;
    if(pipe(fd)<0)
    {
        cout<<"create pipe failed"<<endl;
    }

    pthread_create(&pth_b, NULL, sendMsg, NULL);
    pthread_create(&pth_a, NULL, recevieMsg, NULL);
    pthread_join(pth_a, &retval);
    pthread_join(pth_b, &retval);
    close(fd[1]);
    close(fd[0]);

    return 0;
}



1 编译命令: g++ pipe_twothread.cpp -o testPipe -l pthread
2 两个线程,一个向管道写,一个读,如果在写的时候不usleep(time)一段时间,那么读线程,读出来的数据有问题啊,输出结果来看,管道中没有数据造成的,但是我明明在读的时候检测管道有数据后才读的啊,为什么不对呢??? linux 管道通信 线程
[解决办法]
对任何通讯机制,如果发送方不管接收方是否来得及接收而只管闷头发送的话,都会出问题。
[解决办法]
    char chstr[10];
    int len = 0;
    int err = read(fd[0], chstr, sizeof(chstr));

你按Msg写的,就应该按Msg读,怎么能乱读。。。

热点排行