简体   繁体   中英

Calling every child process at once to kill?

I have to write an program which will generate a random amount of processes, and then will kill them one after one, after they all were created.

My problem is that I can't stop the child processes after being created.

Also, I try to call the termination-output to stdout from a child process, but don't really know how to solve it (because pid = 0 is for every child process).

#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <time.h>
#include <signal.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
    //int status;
    srand(time(NULL));
    int amount = (rand())%9+1;
    pid_t fatherid = getpid();
    printf("Hello I am a parent process, my PID is %d and I will now create %d children.\n",fatherid,amount);
    pid_t pid = 1;
    pid_t pidarr[amount];
    for(int i = 0;i<amount;i++){
        if(pid != 0){
            pid = fork();
            pidarr[i] = pid;
            if(pid ==0){
                printf("Hello I am a child process, my PID is %d and my parent has the PID %d.\n",getpid(),fatherid);
            }
            sleep(1);
        }
    }
    if(pid != 0){
        wait(NULL);
    }
    for(int i = (amount-1);i >= 0;i--){
        if(pidarr[(i-1)] != 0){
            printf("Hello I am a child process %d, I will terminate now.\n",getpid());
        }
        sleep(rand()%4);
        if(pid != 0){
            kill(pidarr[i],SIGKILL);
            printf("Child Process %d was terminated.\n",pidarr[i]);
        }
    }
    if(pid != 0){
        printf("All child processes were terminated. I will terminate myself now.\n");
    }
    return EXIT_SUCCESS;
}

the following code shows how to handle fork and child processes.

the code compiles cleanly, is tested and works

#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <time.h>
#include <signal.h>
#include <sys/wait.h>

int main( void )
{
    //int status;
    srand(time(NULL));

    int amount = (rand())%9+1;

    pid_t fatherid = getpid();

    printf("Hello I am a parent process, my PID is %d and I will now create %d children.\n",fatherid,amount);

    pid_t pid;
    pid_t pidarr[amount];

    for(int i = 0;i<amount;i++)
    {

            pid = fork();
            if( -1 == pid )
            { //then, fork() error
                perror( "fork() failed" );
                exit(1);
            }

            // implied else, fork() successful

            //pidarr[i] = pid;
            if(!pid )
            { // then child process
                printf("Hello I am a child process, my PID is %d and my parent has the PID %d.\n",getpid(),fatherid);
                exit(0);  // exit child process
            }

            // implied else, parent process

            pidarr[i] = pid;           
            sleep(1);
    } // end for

    for(int i = (amount-1); i >= 0; i--)
    {
            kill(pidarr[i],SIGKILL);
            printf("Child Process %d was terminated.\n",pidarr[i]);
    }


    printf("All child processes were terminated. I will terminate myself now.\n");

    return(0);
} // end function: main

I am not sure about other parts of your logic (eg the if clause inside the fork loop), but

if(pid != 0){
   wait(NULL);
}

looks suspiciously as of the parent process waits for a child to exit so that it doesn't get to the code which would kill the children at all (unless they exit on their own, but then the killing seems pointless).

Some issues in your code:

1) As @Peter Schneider points out,

parent process waits for a child to exit so that it doesn't get to the code which would kill the children

So first of all, you have to get rid of:

if(pid != 0){
    wait(NULL);
} 

2) The for loop that kills the children has to be executed only by the parent process, so the if clause embraces the for :

if(pid != 0){
    for(int i = (amount-1);i >= 0;i--){
        kill(pidarr[i],SIGKILL);
        printf("Child Process %d was terminated.\n",pidarr[i]);
    }
}

3) The child processes have to wait doing something until parent kills them, so append the following else clause to the above if :

else{
    while(1){
        printf("I am a child process %d. Will sleep for 2 senconds\n",getpid());
        sleep(2);
    }
}

4) the following code makes no sense, because when children are killed they simply stop working.

if(pidarr[(i-1)] != 0){
    printf("Hello I am a child process %d, I will terminate now.\n",getpid());
}

If you want children to do something when the signal from kill() gets to them, you will have to use signals .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM