Is there a function to end a child process?

79 views Asked by At

I am creating an operating system and I created a child process using C with this code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <windows.h>

int main() {
    FILE *fptr;

    // Open a file in read mode
    fptr = fopen("filename.txt", "r");

    // Store the content of the file
    char myString[100];
    fgets(myString, 100, fptr);
    fclose(fptr);
    PROCESS_INFORMATION ni;
    STARTUPINFO li;
    ZeroMemory(&li, sizeof(li));
    li.cb = sizeof(li);

    if (CreateProcess(NULL, "child_process.exe", NULL, NULL, FALSE, 0, NULL, NULL, &li, &ni)) {
        // Parent process
        WaitForSingleObject(ni.hProcess, INFINITE);
        CloseHandle(ni.hProcess);
        CloseHandle(ni.hThread);
    } else {
        // Child process
    }
    
    pid_t pid = getpid();
    printf("(%d) WARNING: These processes are vital for the OS:\n", pid);
    printf("(%d) %d\n", pid, pid);
    printf("(%d) %s\n\n\n", pid, myString);
    return 0;
}

And I could not end the child process. I do not want to use signals as they are too complex and I am a beginner.

I tried using return 0; and it did not work, the process was still running.

1

There are 1 answers

0
IInspectable On

You terminate a process by calling TerminateProcess(). Doing so will terminate the target process if the caller holds sufficient privileges. This works for any process, not just child processes.

But before you go there, you first need to understand how CreateProcessW() works. The documentation explains the semantics in detail. The return value, in particular, differs from what the code in question assumes.