linux下使用管道pipe和select创建阻塞

来源:互联网 发布:梦娜和浪莎 知乎 编辑:程序博客网 时间:2024/05/17 20:30

linux下使用管道pipe和select创建阻塞的模型,大家参考一下

#include <unistd.h>#include <stdio.h>#include <sys/types.h>#include <sys/wait.h>#include <pthread.h>pthread_t tid;int pip_ios_fd[2] ;struct test{    int* pip_opt;} t1;void* CallBack(void* arg) {    printf("------enter\n");    sleep(3);    printf("------3 unlock\n");    int wret = write(t1.pip_opt[1], "x", 1);    sleep(3);    printf("------3xx\n");    return NULL;}bool select_test() {    int pip_ret = pipe(pip_ios_fd);    int ret_ = pthread_create(&tid, NULL, CallBack, NULL);    pthread_detach(tid);    /* 等待线程也初始化完成 */    fd_set fdsr;    FD_ZERO(&fdsr);    FD_SET(pip_ios_fd[0], &fdsr);    struct timeval tv;    tv.tv_sec = 10;    tv.tv_usec = 0;    t1.pip_opt = pip_ios_fd; //复制管道    int ret = select(pip_ios_fd[0] + 1, &fdsr, NULL, NULL, &tv); //阻塞10s    printf("ret=%d.\n", ret);    if (ret == -1) {     //ret=-1 的时候说明轮巡 出错        printf("error!!!\n");    } else if (ret == 0) { //ret=0 的时候说明轮巡 超时        printf("No data within 10 seconds.\n\n");    } else {//其他情况        printf("------2\n");    }    printf("------4\n");    char c[2];    read(t1.pip_opt[0], c, 2); //默认是阻塞的    printf("c-------------------------->==%s\n", c);    pthread_kill(tid, SIGQUIT);    sleep(10);    return true;}int main(void) {    select_test();    return 0;}


0 0