#include "stdout_watcher.h"
#include <stdio.h>
#include <thread>
#ifdef __GNUC__
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#endif
stdout_watcher::stdout_watcher(QObject *parent) : QThread(parent),
	m_bStop(false)
{

}
void stdout_watcher::stop_and_wait()
{
	m_bStop = true;
	wait();
}
#ifdef __GNUC__

void stdout_watcher::run()
{
	auto pt = [&](FILE * stda,bool stderrb)->void{
		int  stdout_bk; //is fd for stdout backup
		stdout_bk = dup(fileno(stda));
		int pfd_stdout[2];
		pipe2(pfd_stdout,O_NONBLOCK); // O_NONBLOCK);

		// What used to be stdout will now go to the pipe.
		dup2(pfd_stdout[1], fileno(stda));
		while (!m_bStop)
		{
			char buf[1024];
			int red = 0;
			if ((red = read(pfd_stdout[0], buf, 1024)) >0 )
				emit evt_stdata(QByteArray(buf,red),stderrb);
			else
				msleep(10);
		}
		close(pfd_stdout[1]);
		close(pfd_stdout[0]);
		dup2(stdout_bk, fileno(stda));//restore
	};
	std::thread t1(pt, stderr,true);
	std::thread t2(pt, stdout,false);

	t1.join();
	t2.join();
}

#endif
