您的位置:首页 > 运维架构 > Linux

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

2017-01-20 10:10 1206 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  select linux