crystal-lang / crystal

The Crystal Programming Language
https://crystal-lang.org
Apache License 2.0
19.33k stars 1.61k forks source link

Option to launch processes as children #14839

Open stakach opened 1 month ago

stakach commented 1 month ago

Discussion

Process.run to have an option to kill the child if the primary process exits

This simplifies cleaning up worker processes on application exit and provides a method to ensure processes are cleaned up if a process crashes or is forcefully killed

Worker processes in web applications I personally have processes that launch ffmpeg for certain tasks and find it challenging to ensure they are always cleaned up

Linux has the prctl system call with the PR_SET_PDEATHSIG option on linux would do the job (fork -> prctl call -> replace with child process)

BSD has procctl with PROC_PDEATHSIG_CTL

Windows has CreateJobObject to assign workers to a pool which will be cleaned up on exit

crysbot commented 1 month ago

This issue has been mentioned on Crystal Forum. There might be relevant details there:

https://forum.crystal-lang.org/t/child-workers-that-are-automatically-reaped/7047/1

HertzDevil commented 1 month ago

Process already uses CreateJobObjectW on Windows to support IOCP, I don't know if it achieves what you want yet

stakach commented 1 month ago

That's interesting, it's probably very simple to achieve this on Windows then

This is the cpp code to have children terminate when a job object is closed

    // Set the job object to terminate all associated processes when the job is closed
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobInfo = {0};
    jobInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
    if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, &jobInfo, sizeof(jobInfo))) {
        std::cerr << "SetInformationJobObject failed with error: " << GetLastError() << std::endl;
        CloseHandle(job);
        return;
    }

https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-jobobject_basic_limit_information