#include <stdio.h>
#include <windows.h>

int main() {

    SECURITY_ATTRIBUTES sa = { sizeof(sa),NULL,TRUE };

    // Create an inheritable file handle

    HANDLE hFile = CreateFile ("output.txt", FILE_APPEND_DATA, FILE_SHARE_WRITE, &sa, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
    if (hFile == INVALID_HANDLE_VALUE) {
        printf("Failed to create file. Error: %d\n", GetLastError());
        return 1;
    }

// Write to the file
DWORD written;
WriteFile(hFile, "Hello from Parent!\n", 19, &written, NULL);

    // Convert handle to string (so the child process can receive it)
    char handleStr[20];
    sprintf(handleStr, " %llu", (unsigned long long)hFile); // Add a leading space

    // Prepare process startup information
    STARTUPINFO si = { sizeof(si) };
    PROCESS_INFORMATION pi = { 0 };

    // Correctly format the command line
    char cmdLine[150];
    sprintf(cmdLine, "\"C:\\Users\\John\\Documents\\CreateProcess\\child.exe\"%s", handleStr);  

    // Create child process
    if (!CreateProcess(NULL, cmdLine, &sa, &sa, TRUE, 0, NULL, NULL, &si, &pi)) 
   
    {
        printf("CreateProcess failed. Error: %d\n", GetLastError());
        return 1;
    }
Sleep(50);
    printf("Parent: Created child process with PID %d\n", pi.dwProcessId);
    
   // Close handles
    CloseHandle(pi.hProcess);
    CloseHandle(pi.hThread);
    CloseHandle(hFile);
    return 0;
}
