Search code examples
cforkchild-process

Creating num processes with fork and then deleting some that i will not use


Okay so i am making a program and i am creating a number of child processes with fork, letting user decide their number, as such

for(int i=1;i<=number;i++){
        pid_t pid;
        if((pid=fork())<0){
            perror("fork failed");
        }else if(pid==0){ //is a child
            exit(0);
        }
    }
for(int i=1;i<=number;i++)
        wait(NULL);

If the user wants me to create 5 and i create them, but later in my program I only want to use the first 4 lets say, how do i "delete" the last process?


Solution

  • You can use kill:

    #include <sys/types.h>
    #include <signal.h>
    kill(child_pid, SIGKILL);
    

    Edit

    If you want the child process to do some cleanup before exiting, use SIGTERM instead, and in the child process implement a signal handler. Parent:

    kill(child_pid, SIGTERM);
    

    Child:

    void on_sig_term(int sig_num)
    {
        \\ cleanup
        return;
    }
    signal(SIGTERM, on_sig_term);