I have a simple example program that reads from std::cin and writes to std::cout. It works fine if run in cmd.exe or the visual studio debugger. The code (server.cpp):
#include <iostream>
#include <istream>
#include <ostream>
#include <string>
int main(int argc, char* argv[])
{
std::string input;
while (std::getline(std::cin, input))
{
if (input == "dog")
{
std::cout << "cat" << std::endl;
}
else if (input == "white")
{
std::cout << "black" << std::endl;
}
else if (input == "quit")
{
std::cout << "exiting" << std::endl;
return 0;
}
else if (input != "")
{
std::cout << "unknown" << std::endl;
}
}
std::cout << "error" << std::endl;
}
Now I want to run this from another process that writes to its stdin and reads from its stdout. I create two pipes and start a process using CreateProcess with the read handle of one pipe as StdInput handle and the write handle of the other pipe as Stdouput handle. The Code (client.cpp):
#include <Windows.h>
#include <cassert>
#include <iostream>
#include <ostream>
#include <string>
namespace
{
class Server
{
public:
Server() :
m_pi()
{
SECURITY_ATTRIBUTES sa = {sizeof(SECURITY_ATTRIBUTES)};
sa.bInheritHandle = TRUE;
assert(CreatePipe(&m_ro, &m_wo, &sa, 0));
assert(SetHandleInformation(m_ro, HANDLE_FLAG_INHERIT, 0));
assert(CreatePipe(&m_ri, &m_wi, &sa, 0));
assert(SetHandleInformation(m_ri, HANDLE_FLAG_INHERIT, 0));
STARTUPINFO si = {sizeof(STARTUPINFO)};
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdInput = m_ri;
si.hStdOutput = m_wo;
assert(CreateProcess(L"..\\Debug\\server.exe", 0, 0, 0, 1, 0, 0, 0, &si, &m_pi));
}
~Server()
{
execute("quit\n");
assert(WaitForSingleObject(m_pi.hProcess, INFINITE) != WAIT_FAILED);
assert(CloseHandle(m_pi.hThread));
assert(CloseHandle(m_pi.hProcess));
assert(CloseHandle(m_wi));
assert(CloseHandle(m_ri));
assert(CloseHandle(m_wo));
assert(CloseHandle(m_ro));
}
std::string execute(std::string const& cmd)
{
DWORD num_bytes;
assert(WriteFile(m_wi, cmd.c_str(), (DWORD)cmd.size(), &num_bytes, 0));
std::string output;
DWORD n = 0;
while (n == 0)
{
Sleep(0);
assert(PeekNamedPipe(m_ro, 0, 0, 0, &n, 0));
if (n > 0)
{
output.resize(n);
assert(ReadFile(m_ro, &output[0], n, &num_bytes, 0));
}
}
return output;
}
private:
HANDLE m_wo, m_ro, m_wi, m_ri;
PROCESS_INFORMATION m_pi;
};
Server g_server;
}
int main(int argc, char* argv[])
{
std::cout << g_server.execute("white\n") << std::endl;
std::cout << g_server.execute("foobar\n") << std::endl;
std::cout << g_server.execute("dog\n") << std::endl;
}
The problem is that the client only receives the massage "error", so the std::cin of the server seems to be broken.
My question is, what did I do wrong?
You're disabling inheritance for the handle that the child will use to read from stdin - the child needs to inherit that handle. Instead of:
SetHandleInformation(m_ri, HANDLE_FLAG_INHERIT, 0);
Try the following to disable inheritance on the handle that the server process will use to write to the child's stdin:
SetHandleInformation(m_wi, HANDLE_FLAG_INHERIT, 0);
Related
I am making a tester program that opens a console application and reads it's standard input writes to it's standard output, but am having issues with the pipes. I am using named pipes since I might have to run this threaded or even open multiple executables to communicate with at once. These will need to remain running and continuously take input and give out put, as in a console calculator that asks if you if you want another calculation or to exit after each calculation.
Using error checking I have found that The pipes are created successfully, I apply them to the startupInfo struct and successfully open the executable. A note here, if I set a break point in visual studio just after the call to createProcess, the child process does show up in my task manager, the check STILL_ACTIVE is true and peaking at the pipe reveals an empty pipe. If no break point is set then I don't see it, and the check STILL_ACTIVE is false.
To simplify the problem I went back to basics, a simple hello world executable in c++. The calculator will be the next test. This prints hello world to the console and via a cin:get() waits for the enter key to be pressed. I ran this with the tester and tried to read the "Hello World" from the child process. I get nothing.
The end project will be open source, I don't want the user to have to download any other libraries to compile the project, and Boost::Process actually requires 2 install since process is not standard yet.
I know that I am close, here is my simple tester as one file with the process class extracted to be inline in the main. Note: I have enabled c++20 in my compiler.
// Tester.cpp
#include <string>
#include <string_view>
#include <vector>
#include <iostream>
#include <fstream>
#include <filesystem>
#include <io.h>
#include <fcntl.h>
#include <windows.h>
int main()
{
std::string data = "";
int id = 1;
std::string executable = "HelloWorld.exe";
if (_access((executable).c_str(), 0) != -1)
{
std::cerr << "Error: Executable file not found: " << executable << std::endl;
exit(0);
}
SECURITY_ATTRIBUTES saAttr{};
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
//Pipe names
std::wstring pipeErr = L"\\\\.\\pipe\\err_" + std::to_wstring(id);
std::wstring pipeOut = L"\\\\.\\pipe\\out_" + std::to_wstring(id);
std::wstring pipeIn = L"\\\\.\\pipe\\in_" + std::to_wstring(id);
// The Child error pipe for reading
CreateNamedPipeW(pipeErr.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 1024, 1024, 0, NULL);
HANDLE err_pipe = CreateFileW(pipeErr.c_str(), GENERIC_READ | GENERIC_WRITE, 0, &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
// The Child out pipe for reading
CreateNamedPipeW(pipeOut.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT, 1, 1024, 1024, 0, NULL);
HANDLE out_pipe = CreateFileW(pipeOut.c_str(), GENERIC_READ | GENERIC_WRITE, 0, &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
// The Child in pipe for writing
CreateNamedPipeW(pipeIn.c_str(), PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 1, 1024, 1024, 0, NULL);
HANDLE in_pipe = CreateFileW(pipeIn.c_str(), GENERIC_READ | GENERIC_WRITE, 0, &saAttr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL);
if (in_pipe == INVALID_HANDLE_VALUE || out_pipe == INVALID_HANDLE_VALUE || err_pipe == INVALID_HANDLE_VALUE)
{
std::cout << "Error Creating Handles, Code: " << GetLastError() << std::endl;
return 0;
}
// Make sure the handles' inheritance is set correctly
if (!SetHandleInformation(in_pipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) ||
!SetHandleInformation(out_pipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT) ||
!SetHandleInformation(err_pipe, HANDLE_FLAG_INHERIT, HANDLE_FLAG_INHERIT))
{
std::cerr << "Error: Failed to set handle information for the child process" << std::endl;
return 0;
}
// Set up the startup info struct
STARTUPINFOA startupInfo;
memset(&startupInfo, 0, sizeof(startupInfo));
startupInfo.cb = sizeof(STARTUPINFOA);
startupInfo.hStdInput = in_pipe;
startupInfo.hStdOutput = out_pipe;
startupInfo.hStdError = err_pipe;
startupInfo.dwFlags |= STARTF_USESTDHANDLES;
// Set up the process info struct
PROCESS_INFORMATION processInfo;
memset(&processInfo, 0, sizeof(processInfo));
// Create the child process
if (CreateProcessA(NULL, executable.data(), NULL, NULL, TRUE, 0, NULL, NULL, &startupInfo, &processInfo) == 0)
{
std::cerr << "Error: Failed to create the child process" << std::endl;
return 0;
}
// Set the pipes to non-blocking mode
DWORD mode = PIPE_NOWAIT;
SetNamedPipeHandleState(out_pipe, &mode, NULL, NULL);
SetNamedPipeHandleState(err_pipe, &mode, NULL, NULL);
SetNamedPipeHandleState(in_pipe, &mode, NULL, NULL);
Sleep(500); //wait for child to start, may not be neccesary
// Get the exit code of the child process
DWORD exitCode;
GetExitCodeProcess(processInfo.hProcess, &exitCode);
if (exitCode == STILL_ACTIVE) {
// Set up the read buffer
char buffer[1024];
memset(buffer, 0, sizeof(buffer));
DWORD bytesRead = 0;
DWORD bytesAvail = 0;
// Check if there is data available to read from the pipe
if (!PeekNamedPipe(out_pipe, buffer, sizeof(buffer), &bytesRead, &bytesAvail, NULL)) {
std::cerr << "PeekNamedPipe failed (" << GetLastError() << ").\n";
return 0;
}
if (bytesAvail == 0)
{
std::cerr << "Pipe is empty" << std::endl;
}
if (!ReadFile(out_pipe, buffer, sizeof(buffer) - 1, &bytesRead, NULL))
{
std::cerr << "Failed to read from pipe. Error code: " << GetLastError() << std::endl;
return 0;
}
data = buffer;
}
if (data == "") {
std::cout << "Something went wrong. Code: " << GetLastError() << std::endl;
}
else {
std::cout << data << std::endl;
}
std::cout << "Press any key." << std::endl;
std::cin.get();
return 0;
}
and, for reference, here is helloworld.exe:
// HelloWorld.cpp
#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
std::cin.get();
}
Thanks to #Igor Tandetnik!
Here is the working Tester.cpp:
// Tester.cpp
#include <string>
#include <string_view>
#include <vector>
#include <iostream>
#include <fstream>
#include <filesystem>
#include <io.h>
#include <fcntl.h>
#include <windows.h>
#include <aclapi.h>
constexpr auto BUFSIZE = 4096;
int main()
{
std::string data = "";
int id = 1;
std::wstring executable = L"HelloWorld.exe";
std::wstring argv = L"";
std::string name_c = "";
std::string path_c = "";
HANDLE hChildStd_IN_Rd = NULL;
HANDLE hChildStd_IN_Wr = NULL;
HANDLE hChildStd_OUT_Rd = NULL;
HANDLE hChildStd_OUT_Wr = NULL;
HANDLE hChildStd_ERR_Rd = NULL;
HANDLE hChildStd_ERR_Wr = NULL;
size_t size;
wcstombs_s(&size, nullptr, 0, executable.c_str(), executable.length());
name_c.resize(size);
wcstombs_s(&size, name_c.data(), name_c.size(), executable.c_str(), executable.length());
wchar_t current_dir[FILENAME_MAX];
if (_wgetcwd(current_dir, FILENAME_MAX) == nullptr) {
std::cerr << "Error getting current working directory. Code:" << GetLastError() << std::endl;
exit(0);
}
wchar_t path_exe[MAX_PATH];
GetModuleFileName(NULL, path_exe, MAX_PATH);
std::wstring path = path_exe;
path = std::filesystem::path(path).parent_path();
path += L"\\";
path += executable;
wcstombs_s(&size, nullptr, 0, path.c_str(), path.length());
path_c.resize(size);
wcstombs_s(&size, path_c.data(), path_c.size(), path.c_str(), path.length());
int found = _waccess_s(path.c_str(), 0);
if (found != 0)
{
std::cerr << "Error: Executable file not found: " << name_c << std::endl;
exit(0);
}
SECURITY_ATTRIBUTES sa_attr{};
sa_attr.nLength = sizeof(SECURITY_ATTRIBUTES);
sa_attr.bInheritHandle = TRUE;
sa_attr.lpSecurityDescriptor = NULL;
// Create the pipes
if (!CreatePipe(&hChildStd_OUT_Rd, &hChildStd_OUT_Wr, &sa_attr, 0)
|| !CreatePipe(&hChildStd_IN_Rd, &hChildStd_IN_Wr, &sa_attr, 0)
|| !CreatePipe(&hChildStd_ERR_Rd, &hChildStd_ERR_Wr, &sa_attr, 0)) {
std::cout << "Error Creating Pipes, Code: " << GetLastError() << std::endl;
return 1;
}
if (hChildStd_OUT_Rd == INVALID_HANDLE_VALUE || hChildStd_OUT_Wr == INVALID_HANDLE_VALUE
|| hChildStd_IN_Rd == INVALID_HANDLE_VALUE || hChildStd_IN_Wr == INVALID_HANDLE_VALUE
|| hChildStd_ERR_Rd == INVALID_HANDLE_VALUE || hChildStd_ERR_Wr == INVALID_HANDLE_VALUE)
{
std::cout << "Error Creating Handles, Code: " << GetLastError() << std::endl;
return 1;
}
// Set up the startup info struct
STARTUPINFOW startup_info;
ZeroMemory(&startup_info, sizeof(STARTUPINFOW));
startup_info.cb = sizeof(STARTUPINFOW);
startup_info.hStdOutput = hChildStd_OUT_Wr;
startup_info.hStdError = hChildStd_ERR_Wr;
startup_info.hStdInput = hChildStd_IN_Rd;
startup_info.dwFlags |= STARTF_USESTDHANDLES;
// Set up the process info struct
PROCESS_INFORMATION process_info;
memset(&process_info, 0, sizeof(process_info));
// Create the child process
if (!CreateProcess(path.data(), NULL, &sa_attr, NULL, TRUE, 0, NULL, NULL, &startup_info, &process_info))
{
std::cerr << "Error: Failed to create the child process. Code: " << GetLastError() << std::endl;
return 1;
}
// Get the exit code of the child process
DWORD exitCode;
GetExitCodeProcess(process_info.hProcess, &exitCode);
if (exitCode != STILL_ACTIVE) {
std::wcout << "Unable to Start Process: " << executable.c_str() << std::endl;
return 1;
}
std::wcout << "Started Process: " << executable.c_str() << std::endl;
Sleep(500); //wait for child to start, may not be neccesary
// Get the exit code of the child process
GetExitCodeProcess(process_info.hProcess, &exitCode);
if (exitCode == STILL_ACTIVE) {
// Set up the read buffer
DWORD bytesRead{}, dwWritten{};
CHAR buffer[BUFSIZE]{};
BOOL bSuccess = FALSE;
HANDLE hParentStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
bSuccess = ReadFile(hChildStd_OUT_Rd, buffer, BUFSIZE, &bytesRead, NULL);
if (!bSuccess || bytesRead == 0)
{
std::cerr << "Failed to read from pipe. Error code: " << GetLastError() << std::endl;
return 1;
}
std::vector<char> v_data(buffer, buffer + bytesRead);
data = std::string(v_data.data(), v_data.size());
}
std::cout << "Recieved from Child: " << data << std::endl;
if (data == "") {
std::cout << "Something went wrong. Code: " << GetLastError() << std::endl;
return 1;
}
else {
std::cout << data << std::endl;
}
CloseHandle(process_info.hThread);
std::cout << "Press any key." << std::endl;
std::cin.get();
return 0;
}
This question already has answers here:
FindFirstChangeNotification is notifying about changes twice
(2 answers)
Closed 1 year ago.
I have to find out if there is a new file in a directory on Windows. Following this MSDN example (Obtaining Directory Change Notifications), I came up with the following test program:
#include <iostream>
#include <Windows.h>
#include <vector>
#include <string>
std::string FindNewFile(std::vector<std::string>& vsNewFileList, std::vector<std::string>& vsOldFileList)
{
std::string sNewFileName;
int nScore = 0;
for (auto& newFile : vsNewFileList)
{
nScore = 0;
for (auto& oldFile : vsOldFileList)
if(!newFile.compare(oldFile))
nScore++;
if (nScore!=1)
{
sNewFileName = newFile;
break;
}
}
return sNewFileName;
}
void GetCurrentFilesInDir(std::string sDir, std::vector<std::string>& vsFileList)
{
WIN32_FIND_DATA ffd;
sDir += "\\*";
std::wstring wStr = std::wstring(sDir.begin(), sDir.end());
LPCWSTR lpcwsDir = (LPCWSTR)wStr.c_str();
HANDLE hFind = FindFirstFile(lpcwsDir, &ffd);
if (hFind == INVALID_HANDLE_VALUE)
{
std::cout << "Nope\n";
return;
}
vsFileList.clear();
do
{
int nSize = WideCharToMultiByte(CP_ACP, 0, ffd.cFileName, -1, 0, 0, 0, 0);
char* pcStr = new char[nSize];
WideCharToMultiByte(CP_ACP, 0, ffd.cFileName, -1, pcStr, nSize, 0, 0);
//std::cout << pcStr << "\n";
vsFileList.push_back(std::string(pcStr));
delete[] pcStr;
} while (FindNextFile(hFind, &ffd) != 0);
}
int main()
{
// watch the foo directory for new files
std::string sDir = "C:\\foo";
std::vector<std::string> vsOldFileList, vsNewFileList;
GetCurrentFilesInDir(sDir, vsOldFileList);
std::wstring wStr = std::wstring(sDir.begin(), sDir.end());
LPCWSTR lpcwsDir = (LPCWSTR)wStr.c_str();
DWORD dwWaitStatus;
HANDLE dwChangeHandle;
dwChangeHandle = FindFirstChangeNotification(
lpcwsDir,
FALSE,
FILE_NOTIFY_CHANGE_FILE_NAME);
while (TRUE)
{
// returns multiple times before and after new file appears!!
dwWaitStatus = WaitForSingleObject(dwChangeHandle, INFINITE);
switch(dwWaitStatus)
{
case WAIT_OBJECT_0:
GetCurrentFilesInDir(sDir, vsNewFileList);
std::string sNewFileName = FindNewFile(vsNewFileList, vsOldFileList);
std::cout << sNewFileName << "\n";
GetCurrentFilesInDir(sDir, vsOldFileList);
FindNextChangeNotification(dwChangeHandle);
break;
}
}
}
The problem is that, when I save a new file in C:\foo (for instance, using Notepad++ to "Save As" an open .txt file in C:\foo), the call to WaitForSingleObject() in the while loop will return 0 multiple times. Since my FindNewFile() method returns an empty string if there is no new file in the directory, I will get output like:
a.txt
or:
b.txt
Or even:
c.txt
c.txt
Can someone explain what I am missing here?
Using FindNextChangeNotification can not tell you what actually happened, and the operation of the file may involve multiple changes.
You can try to use ReadDirectoryChangesW and here is a sample:
#include <windows.h>
#include <iostream>
using namespace std;
wstring getname(FILE_NOTIFY_INFORMATION* tmp)
{
wstring s = L"";
for (int i = 0; i < tmp->FileNameLength / 2; i++)
s += tmp->FileName[i];
return s;
}
int main(int argc, const char* argv[])
{
HANDLE hDir;
char notify[1024];
DWORD cbBytes;
LPTSTR path;
FILE_NOTIFY_INFORMATION* pnotify = (FILE_NOTIFY_INFORMATION*)notify;
FILE_NOTIFY_INFORMATION* tmp;
// GetCurrentDirectory(MAX_PATH,path.GetBuffer(MAX_PATH+1));
path = (LPTSTR)L"D:\\test";
hDir = CreateFile(path, FILE_LIST_DIRECTORY,
FILE_SHARE_READ |
FILE_SHARE_WRITE |
FILE_SHARE_DELETE, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS |
FILE_FLAG_OVERLAPPED, NULL);
wcout << L"===CreateFile complete===" << endl;
if (hDir == INVALID_HANDLE_VALUE)
{
wcout << L"invalid handle value" << endl;
return -1;
}
FILE_NOTIFY_INFORMATION buffer[1024];
FILE_NOTIFY_INFORMATION* pbuffer;
while (TRUE)
{
wcout << L"waiting..." << endl;
WaitForSingleObject(hDir, INFINITE);
if (ReadDirectoryChangesW(hDir, &buffer, sizeof(buffer),
TRUE, FILE_NOTIFY_CHANGE_FILE_NAME,
&cbBytes, NULL, NULL))
{
pbuffer = buffer;
do {
tmp = pbuffer;
switch (tmp->Action)
{
case FILE_ACTION_ADDED:
wcout << L"Directory/File added - " << getname(tmp) << endl;
break;
case FILE_ACTION_REMOVED:
wcout << L"Directory/File removed - " << getname(tmp) << endl;
break;
case FILE_ACTION_MODIFIED:
wcout << L"Directory/File modfied - " << getname(tmp) << endl;
break;
case FILE_ACTION_RENAMED_OLD_NAME:
wcout << L"Directory/File old name - " << getname(tmp) << endl;
break;
case FILE_ACTION_RENAMED_NEW_NAME:
wcout << L"Directory/File new name - " << getname(tmp) << endl;
break;
default:
wcout << L"unknown action\n" << endl;
break;
}
pbuffer += pbuffer->NextEntryOffset;
} while (pbuffer->NextEntryOffset);
}
else
{
wcout << "readChangesW failed now return" << endl;
return -1;
}
}
}
When you do the Save As operation, you will find:
Therefore, multiple file operations were triggered when actually saving as, and you also performed multiple comparisons when processing new file comparisons, so empty characters were output.
More reference: FindFirstChangeNotification is notifying about changes twice
I haven't been able to find anything else about this online at all. I have a simple authenticator program, with a .dll injector written into it. If the key matches the one in the database, it will run the injector, and constantly check to make sure that the key is still active. For some reason, my console window outputs "tick" about every second. When the injector is taken out, and it is just the authenticator it will not do this.
#include <iostream>
#include <string>
#include <Windows.h>
#include <thread>
#include <WinInet.h>
#include <TlHelp32.h>
#include <fcntl.h>
#include <io.h>
#include <fcntl.h>
#include <cstdio>
#include <chrono>
#include "include/c0gnito.h"
std::string Key;
std::string hwid = GetHardwareID(); //Gets the hwid
char* StringToChar(std::string string) //A function to convert a string to a char
{
return _strdup(string.c_str());
}
template <class T>
void msg(T msg)
{
std::cout << msg << std::endl;
}
bool FileExists(const std::string& fileName)
{
struct stat buffer;
return (stat(fileName.c_str(), &buffer) == 0);
}
void WriteStringToIni(std::string string, std::string file, std::string app, std::string key)
{
WritePrivateProfileStringA(app.c_str(), key.c_str(), string.c_str(), file.c_str());
}
std::string ReadStringFromIni(std::string file, std::string app, std::string key)
{
char buf[100];
GetPrivateProfileStringA(app.c_str(), key.c_str(), "NULL", buf, 100, file.c_str());
return (std::string)buf;
}
LONG address = 0x0;
BYTE newvalue[] = { 0x0 };
HWND hwnd;
HANDLE phandle;
DWORD pid;
DWORD GetProcId(const char* procName)
{
DWORD procId = 0;
HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hSnap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 procEntry;
procEntry.dwSize = sizeof(procEntry);
if (Process32First(hSnap, &procEntry))
{
do
{
if (!_stricmp(procEntry.szExeFile, procName))
{
procId = procEntry.th32ProcessID;
break;
}
} while (Process32Next(hSnap, &procEntry));
}
}
CloseHandle(hSnap);
return procId;
}
const char* dllPath = "C:\\Windows\\System32\\sysproc.dll";
const char* procName = "Project1.exe";
DWORD procId = 0;
int main() //Entry point
{
system("color b"); //Sets the color to blue
Initialize("B2wVksYPzgCBOtNq8SFQ05GCuKrzwNIRytotMczYWCSv59sypLJhPEnLY9w8cmml"); //Connects to the authentication server
if (FileExists("./Config.ini"))
{
Key = ReadStringFromIni("./Config.ini", "License", "Key"); //Gets the key saved in the file
}
else
{
std::cout << "Welcome, please enter your license key: ";
std::cin >> Key; //Gets the user's key
if (Authenticate(StringToChar(Key), (StringToChar(hwid)))) {}// Authenticates key & hwid
else
{
std::cout << "Invalid Key!" << std::endl;
exit(2000);
}
WriteStringToIni(Key, "./Config.ini", "License", "Key"); //Creates a file that stores the key entered
}
if (Authenticate(StringToChar(Key), (StringToChar(hwid)))) // Authenticates key & hwid
{
std::cout << "Sucessfully Authenticated!" << std::endl;
Sleep(2000);
while (!procId)
{
procId = GetProcId(procName);
Sleep(30);
}
HANDLE hProc = OpenProcess(PROCESS_ALL_ACCESS, 0, procId);
if (hProc && hProc != INVALID_HANDLE_VALUE)
{
void* loc = VirtualAllocEx(hProc, 0, MAX_PATH, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
WriteProcessMemory(hProc, loc, dllPath, strlen(dllPath) + 1, 0);
HANDLE hThread = CreateRemoteThread(hProc, 0, 0, (LPTHREAD_START_ROUTINE)LoadLibraryA, loc, 0, 0);
if (hThread)
{
CloseHandle(hThread);
}
}
if (hProc)
{
CloseHandle(hProc);
}
}
else
{
exit(0);
}
system("cls");
std::cout << "Hardware ID: " << hwid << std::endl;
std::cout << "_______________________________________________________" << std::endl;
std::cout << " " << std::endl;
std::thread auth([&]() //Authentication Thread that keep on checking the connection and user previleges
{
while (true)
{
std::cout << "Auth is checking..." << std::endl;
if (!Authenticate(StringToChar(Key), (StringToChar(hwid))))
{
exit(0);
}
std::cout << "Sucessfully Authenticated!" << std::endl;
Sleep(60000);
}
});
std::cin.get();
}
I have a scenario where a spawned child process is killed when the parent is killed with SIGABRT. In my understanding, the child should continue to run. To mimic the actual code, I created two files presenting child and parent. The parent writes to a pipe and child reads from the read end (STDIN_FILENO).
parent code -> parent.cpp
#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
int main() {
int pipefd[2];
std::string message = "test\n";
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
int pid = fork();
if (0 == pid) {
std::cout << "Inside child process\n";
close(pipefd[1]);
char *args[] = {"./CHILD", NULL};
char *envp[] = {NULL};
if (dup2(pipefd[0], STDIN_FILENO) == -1) {
std::cout << "dup2 failed\n";
}
close(pipefd[0]);
close(pipefd[1]);
execve(args[0], args, envp);
} else {
close(pipefd[0]);
while (1) {
sleep(1);
std::cout << "parent writing -> " << message;
write(pipefd[1], message.c_str(), message.length());
}
}
return 0;
}
child code -> child.cpp
#include <iostream>
#include <string>
#include <unistd.h>
int main() {
std::string str;
char buf;
std::cout << "[child] started\n";
while (read(STDIN_FILENO, &buf, sizeof(buf)) > 0) {
if (buf != '\n')
str += buf;
else {
write(STDOUT_FILENO, str.c_str(), str.length());
str.clear();
write(STDOUT_FILENO, "\n", 1);
}
}
std::cout << "[child] Exiting the application\n";
return 0;
}
if the parent is killed with SIGABRT, the child also receives the same. When the pipe code is removed, the signal is not propagated.
Can you please provide some insight into it?
I want to analyse the output of strace in my C++ program. While launching /bin/strace ps from my app I get an output from ps, but not from strace and strace output is printed to stdout (my terminal). I use standard technique of using pipes and redirecting streams.
Here is my source:
#include <stdlib.h>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
char *const parmList[] = {"/bin/strace", "ps", NULL};
int pipes[2];
pipe(pipes);
pid_t child = fork();
if(child == 0){
close(pipes[0]);
dup2(pipes[1],1);
execv(parmList[0], parmList);
}
else{
int status;
wait(&status);
fcntl(pipes[0], F_SETFL, O_NONBLOCK | O_ASYNC);
char buf[128] = {0};
ssize_t bytesRead;
std::string stdOutBuf;
while(1) {
bytesRead = read(pipes[0], buf, sizeof(buf)-1);
if (bytesRead <= 0)
break;
buf[bytesRead] = 0;
stdOutBuf += buf;
}
std::cout << "<stdout>\n" << stdOutBuf << "\n</stdout>" << std::endl;
}
close(pipes[0]);
close(pipes[1]);
return 0;
}
How can I get an output of strace in my program?
strace writes to stderr not to stdout, if you only want to capture the strace output just use stderr instead of stdout
change the dup2 line like this
dup2(pipes[1],2);
If you want combined strace and ps output do this:
dup2(pipes[1],1);
dup2(pipes[1],2);
if you want separated output you'll probably need to use non-blocking reads and select() or poll()
Also: after calling exec you should print an error message, if everything works exec won't return, but if something goes wrong with the exec, it's good to know.
std::cerr << "exec failed!";
I used this code and had success:
#include <stdlib.h>
#include <iostream>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <fcntl.h>
int main(){
char *const parmList[] = {"/usr/bin/strace", "ps", NULL};
int pipes[2];
pipe(pipes);
pid_t child = fork();
if(child == 0){
close(pipes[0]);
dup2(pipes[1],2);
execv(parmList[0], parmList);
std::cerr << "exec fail\n" ;
}
else{
int status;
wait(&status);
fcntl(pipes[0], F_SETFL, O_NONBLOCK | O_ASYNC);
char buf[128] = {0};
ssize_t bytesRead;
std::string stdOutBuf;
while(1) {
bytesRead = read(pipes[0], buf, sizeof(buf)-1);
if (bytesRead <= 0)
break;
buf[bytesRead] = 0;
stdOutBuf += buf;
}
std::cout << "<stdout>\n" << stdOutBuf << "\n</stdout>" << std::endl;
}
close(pipes[0]);
close(pipes[1]);
return 0;
}
HTH