pipe unblock select in linux

来源:互联网 发布:源码解密 编辑:程序博客网 时间:2024/06/07 01:29
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>


int pipefd[2];

int buf;


//when sub thread  get 'q' char , then write 'q' to pipe, main thread will get it throug read , 

void assisthread(void *arg)
{
    int c;
    int sum = 0;
    while( 1 ){
        c = getchar();

        if (c == 'q'){
            write(pipefd[1],&c,1);
            sum ++;

            sleep(3);

            printf("get the q char \n");
                break;
        }
    }


    pthread_exit(0);
}


int main(void)
{
    pthread_t assistthid;
    int status;

    fd_set rfds;
    struct timeval tv;
    int retval;

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    FD_ZERO(&rfds);
    FD_SET(pipefd[0], &rfds);

    pthread_create(&assistthid,NULL,(void *)assisthread,NULL);

    tv.tv_sec = 0;
    tv.tv_usec = 0;


    while (1 ) {

        retval = select(pipefd[0]+1, &rfds, NULL, NULL, &tv);

        if (retval == -1)
            perror("select()");
        else if (retval) {
            printf("Data is available now.\n");
            if(read(pipefd[0],&buf,1) > 0){                                               //main thread get the 'q' from subthread, then quit.
                printf("buf is %d,and 'q' is %d \n",buf,'q');
                if ( buf == 'q' ) {
                   sleep(3);
                   printf("get the q char will break;\n");
                   break;
                }
            }
        }
        else
            printf("No data within five seconds. retval = %d\n",retval);


        FD_ZERO(&rfds);
        FD_SET(pipefd[0], &rfds);


    }


    pthread_join(assistthid,(void *)&status);
    printf("assistthread's exit is caused %d \n",status);


    return 0;
}


build  gcc main.c -o thread -lpthread

原创粉丝点击