您的位置:首页 > Web前端

控制台程序的标准输入输出的重定向

2007-04-22 11:24 253 查看
 控制台程序的标准输入输出的重定向
今天终于解决这个问题困扰我几个月的问题,心里很高兴!!!
在使用重定向技术需要注意以下几个问题:
1、子进程程序每一句输出代码后需要调用fflush(stdout)函数,这样把输出的内容放入缓冲区,父进程才能及时的读到输出数据
2、如果不是使用fflush(stdout)函数,子进程使用gets()函数会阻止子进程的线程运行
3、重定向最好使用完成端口,这样可以一个线程处理很多的重定向子进程,减少线程数量

下面是我测试的代码

// stdafx.h : 标准系统包含文件的包含文件,
// 或是常用但不常更改的项目特定的包含文件
//

#pragma once

#include <iostream>
#include <tchar.h>
#include <windows.h>
#include <process.h>

// TODO: 在此处引用程序要求的附加头文件
// ClientServ.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <deque>
using namespace std;

bool q=false;

unsigned int _stdcall ThreadOne(void* param)
{
    int * id=(int*)param;
    printf("线程%d运行/r/n",*id);
    fflush(stdout);
    float num=0;
    while(!q)
    {
        num++;
        printf("线程%d第%f次输出消息/r/n",*id,num);
        fflush(stdout);
        Sleep(1000);
    }
    printf("线程%d停止/r/n",*id);
    fflush(stdout);
    return 0;
}

int _tmain(int argc, _TCHAR* argv[])
{
    char buffer[256];
    printf("子进程开始运行/r/n");
    fflush(stdout);
    long int i=0;
    int id1=1;
    unsigned tid;
    HANDLE hwnd=NULL;
    hwnd=(HANDLE)_beginthreadex(NULL,0,&ThreadOne,&id1,0,&tid);
    if(hwnd)
    {
        ::CloseHandle(hwnd);
    }
    //与父进程进行命令交互
    while(1)
    {
        memset(buffer, 0, 256);
        gets(buffer);
        if (!strcmp(buffer,"quit"))
        {
            q=true;
            printf("正在终止线程/r/n");
            fflush(stdout);
            Sleep(2000);
            break;
        }  
    }
    printf("子进程退出/r/n");
    fflush(stdout);
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息