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

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 callBack\n");
    sleep(3);
    printf("------ unlock\n");
    int wret = write(t1.pip_opt[1], "x", 1); //当往管道写入时 SELECT 解除阻塞
    sleep(3);
    printf("------ check is over\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("------ ok\n");
    }

    printf("------go to read\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;
}




  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值