Find the answer to your Linux question:
Results 1 to 3 of 3
The code below creates 10 processes and then calls function(); which is kept in another file. Code: for (i=0; i<10; i++) { switch (pid = fork()) { case -1: printf("Fork ...
  1. #1
    Just Joined!
    Join Date
    Oct 2007
    Posts
    12

    posix fork, killing all child processes

    The code below creates 10 processes and then calls function(); which is kept in another file.
    Code:
            for (i=0; i<10; i++)
            {
                    switch (pid = fork())
                    {
                            case -1:
                                    printf("Fork Error\n");
                                    break;
                            case 0:
                                    function(); //in another file
                                    break;
                    }
                    
            }
    1) how do i find out each processes pid? (within main code block above)
    or how do i kill all of the child processes?

  2. #2
    Linux Guru Rubberman's Avatar
    Join Date
    Apr 2009
    Location
    I can be found either 40 miles west of Chicago, or in a galaxy far, far away.
    Posts
    8,974
    Your code is not likely doing what you want. In your example, each forked child process will continue to fork additional threads after returning from function(). So, instead of a break after function(), you should call exit(0) which will terminate the child while the parent process continues to fork the children you asked for. Also, fork() returns a pid_t type, which is the child process ID. If it is -1, you have an error (as you obviously know). If 0 then you are in the child process context. If other than 0 or -1, then you have a valid process ID of the child process in the context of the parent forking process. So, you might want to do this:
    Code:
            for (i=0; i<10; i++)
            {
                    switch (pid = fork())
                    {
                            case -1: // Error
                                    printf("Fork Error\n");
                                    break;
                            case 0: // Child process
                                    function(); //in another file
                                    exit(0);
                            default: // In parent process
                                    printf("Child (%d) Created\n", (int)pid);
                                    break;
                    }
            }
    Sometimes, real fast is almost as good as real time.
    Just remember, Semper Gumbi - always be flexible!

  3. #3
    Just Joined!
    Join Date
    Oct 2007
    Posts
    12
    Thanks, that is exactly what i was needing, I will have to read up a bit more how forking is used/works.

    Thanks again.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...