So my task goes like this:
The program needs 2 processes in one main function
Note that I am aware that the program itself is a process, but it needs to be done like that. There are some "tips" to use a file as mutex (CreateFile parameters) that would be the dsShareMode with FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE parameter.
Now my question is: how do you create 2 processes to handle its own line of code? I've seen many examples of CreateProcess
function but I don't really understand the first two parameters of this function
What am I supposed to pass to it in order to run 2 processes, one to handle the user input and the other to be the "monitor"?
The first process is meant to handle those lines of code:
std::string buffer;
std::cout << "Enter your text:" << std::endl;
getline(std::cin, buffer);
HANDLE hFile = CreateFile("log.txt", FILE_APPEND_DATA, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
DWORD written = 0;
WriteFile(hFile, buffer.c_str(), buffer.size(), &written, NULL);
While the second process should only care about this:
hFile = CreateFile("log.txt", FILE_READ_ATTRIBUTES, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (hFile == INVALID_HANDLE_VALUE)
{
std::cout << "CreateFile error " << GetLastError() << std::endl;
}
else
{
DWORD size = GetFileSize(hFile, NULL);
std::cout << "\nCurrent file size: " << size << std::endl;
CloseHandle(hFile);
}
int stringLength = 0;
for(int i=0; buffer[i]; i++)
stringLength++;
std::cout << "\nCharacters given since last startup: " << stringLength << std::endl;
Assuming you have a separate helper.exe
, you can do:
CreateProcess(nullptr, "helper logger-mode", ...)
and
CreateProcess(nullptr, "helper monitor-mode", ...)
This will create two processes that see either logger-mode
or monitor-mode
in their second argument (argv[1]
).