Search code examples
c++createprocesscreatefile

Two processes handling their own lines of code in one main function (c++)


So my task goes like this:

The program needs 2 processes in one main function

  • First process creates or opens a file "log.txt" which is in the same directory where the program is located. Then it adds user input to this file.
  • Second process is a "monitor" of this file. It checks if the file exists, shows its size and shows how many characters were entered since the second process started.

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

  • lpApplicationName and
  • lpCommandLine

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;

Solution

  • 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]).