0

I have have an application that forks quite a few child processes. I would like to store these child pid's in an array so when MAX_CHILD is reached. I can kill off the oldest ones.

Any way of accomplishing this ?

note... In my real application I fork and do not wait for process to finish

here is a test snippet...

---main

 pid_t pid;

    if ((pid = fork()) < 0) {
        printf("[*]- ERROR -> Fork returned -1\n\n");
    }

    else if (pid == 0) {
        // Success
        // Child process begins here
        printf("Inside Child @ PID %i . Check ps\n", pid);
        sleep(30);
    }

    else {
        // Still good here
        // Maybe store pid to global array here?
        printf("Back to parent PID: %i CHILD: %i\n\n", getpid(), pid);
    }

    // pid comes out as 0 here as expected
    printf("PID: %i\n", pid);

So I would like to store pid into a int array maybe? How do you correctly cast pid_t? I want to be able to call a cleanup() function and have it step through a list of child PIDs to see if they are still active, if yes, then kill the oldest.

Any advice would be appreciated. Thank you.

user2815333
  • 486
  • 1
  • 3
  • 9
  • Your design sounds poor. – Jonathon Reinhart Apr 17 '14 at 00:14
  • 2
    Why do you need to cast? What's wrong with a container of `pid_t`s? – Carl Norum Apr 17 '14 at 00:14
  • I didn't know I could do that. How would this be globally? – user2815333 Apr 17 '14 at 00:18
  • @Jonathon Reinhart, it's very poor. I'm going to eventually change it over to threads. Just trying to learn here – user2815333 Apr 17 '14 at 00:20
  • 2
    @user2815333, you can make an array of any type. – Carl Norum Apr 17 '14 at 00:24
  • 1
    `pid_t myArray[maxChildren]` You really need to think through what you are planning. If you are going to be creating and killing children a list might be more convenient than an array. You *should* wait on your children in the real code - how else are you going to know when they die? It's easier to code, less error prone, and more efficient than polling your children with `kill` to see if they are still alive. – Duck Apr 17 '14 at 01:00

0 Answers0