Here's some code I'm working on. I'm a beginning programmer and i'm doing this as a (useful) experiment so that i can access my command prompt on my home machine when I'm away.
It was really an excuse to learn about pipes and inheritence etc.
Basically from what I can tell from learning about pipes, I've to pass the write-only handle of the pipe to the process, making its stdout send to the pipe.
The problem is that when I try to read from the anonymous pipe there's nothing to read. I don't know if this is the fault of the launched processes stdout setup or the fault of the pipe setup, though when I use WriteFile to write to the pipe I still can't read anything from it.
I see from the example in the SDK that they're using DuplicateHandle for some reason. I don't understand why at all.
Any help would be appreciated, I'm really stuck with this.
Code:
#include "stdafx.h"
#include "resource.h"
#include <windows.h>
#include <winsock2.h>
#define BUFFERSIZE 1024
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd)
{
//Starting winsock
WSADATA test_wsa;
int Sockreturn= WSAStartup(MAKEWORD(2,2),&test_wsa);
if ( Sockreturn != NO_ERROR ) return 1;
//Making socket
sockaddr_in test_sin;
SOCKET test_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if ( test_socket == INVALID_SOCKET ) return 1;
//Socket settings
test_sin.sin_family = AF_INET;
test_sin.sin_port = htons(808);
test_sin.sin_addr.s_addr = inet_addr("127.0.0.1");
//Connecting socket
Sockreturn = connect(test_socket, (SOCKADDR *) &test_sin, sizeof(test_sin));
if ( Sockreturn == SOCKET_ERROR ) return 1;
//***************************************
//makethepipe();
HANDLE out_hread, out_hwrite;
SECURITY_ATTRIBUTES sa;
PROCESS_INFORMATION pi;
STARTUPINFO si;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
//Make pipe handle inheritable
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
//Make pipe
CreatePipe(&out_hread,&out_hwrite,&sa,0);
//Make stdout of cmd.exe write
si.hStdOutput = out_hwrite;
si.dwFlags = STARTF_USESTDHANDLES;
int x = CreateProcess(NULL,"cmd.exe", NULL, NULL, TRUE, NULL, NULL, NULL, &si, &pi);
char pipereadbuffer[BUFFERSIZE];
DWORD pointlessvariable;
while (1)
{
if(ReadFile(&out_hread,pipereadbuffer, 5, &pointlessvariable, NULL))
{
//Send some data (test purposes)
send(test_socket, "test", 6, 0);
Sleep(100);
break;
}
}
//***************************************
return 1;
}