vs控制台非阻塞实时输入和阻塞按行输入

参考网址:http://blog.csdn.net/hemeinvyiqiluoben/article/details/9098107


代码:


#include "stdafx.h"
#include <windows.h>
#include <process.h>
#include <stdio.h>
#include <iostream>
#include <string>


#define BUFFER_MAX 1024


char g_nbstdin_buffer[2][BUFFER_MAX];
HANDLE g_input[2];
HANDLE g_process[2];


DWORD WINAPI console_input(LPVOID lpParameter)
{
for (;;) {
int i;
for (i = 0; i<2; i++) {
fgets(g_nbstdin_buffer[i], BUFFER_MAX, stdin);
SetEvent(g_input[i]);
WaitForSingleObject(g_process[i], INFINITE);
}
}
return 0;
}


void create_nbstdin()
{
int i;
DWORD tid;
CreateThread(NULL, 1024, &console_input, 0, 0, &tid);
for (i = 0; i<2; i++) {
g_input[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
g_process[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
g_nbstdin_buffer[i][0] = '\0';
}
}


const char* nbstdin()
{
DWORD n = WaitForMultipleObjects(2, g_input, FALSE, 0);
if (n == WAIT_OBJECT_0 || n == WAIT_OBJECT_0 + 1) {
n = n - WAIT_OBJECT_0;
SetEvent(g_process[n]);
return g_nbstdin_buffer[n];
}
else {
return 0;
}
}


void main()
{
create_nbstdin();


bool runing = false;
for (;;) {
if (runing) {
const char *line = nbstdin();
if (line) {
printf(">%s", line);
if (!strcmp(line, "s\n")) {
runing = false;
printf("stop");
}
else {
printf("runing...");
}
}
else {
Sleep(1);
}
}
else {
char buffer[40];
memset(buffer,0,40);
std::cin.getline(buffer,40);
if (!strcmp(buffer, "run")) {
runing = true;
}
printf(buffer);
}


}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值