#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
/* gcc defined unix */
#ifdef unix
#include <unistd.h>
#endif
#ifdef WIN32
#include <io.h>
#define pipe(X) _pipe(X,40,O_BINARY)
#define fileno _fileno
#define dup2 _dup2
#define read _read
#endif
#include <assert.h>
int main()
{
int fds[2];
int res;
char buf[256];
int so;
res = pipe(fds);
assert(res == 0);
so = fileno(stdout);
//close stdout handle and make the writable part of fds the new stdout.
res = dup2(fds[1], so);
assert(res != -1);
//printf("Hi theren3333333");
system("dir");
fflush(stdout);
//reading should happen in a different thread
res = read(fds[0], buf, sizeof(buf) - 1);
assert(res >= 0 && res < sizeof(buf));
buf[res] = 0;
fprintf(stderr, "buf=>%s --->n", buf);
return 0;
}
原文:https://www.cnblogs.com/thinkinc999/p/13261747.html