Thread: Multiple processes running concurrently in c

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    30

    Multiple processes running concurrently in c

    Is this how you do it?

    Code:
    int main(int argc, char *argv[])
    {
            int i = 0;
            for(i=0;i<argc;i++)
            {
                    if(fork() == 0)
                    {
                            printf("child %d\n", i);
                            exit(1);
                    }
            }
            return 0;
    }
    If not, why not? And how? The key thing I want most if that all the processes run at the same time.

  2. #2
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    Try it and see! Print out the result of getpid():
    Code:
    if (fork() == 0) {
        printf("child %d pid %d\n", i, getpid());
        exit(1);
    } else {
        printf("pid %d\n", getpid());
    }
    /*if they're different, you win*/
    Although, making as many processes as argc seems next to useless..

  3. #3
    Registered User
    Join Date
    May 2011
    Posts
    30
    Thank you, and the processes to argcs is for a bigger purpose, this was just a test.

  4. #4
    Registered User
    Join Date
    Dec 2011
    Posts
    795
    Quote Originally Posted by bungkai View Post
    Thank you, and the processes to argcs is for a bigger purpose, this was just a test.
    Ah okay, cool.

    What are you doing, by the way? A lot of the problems that can be solved with fork() can also be solved with threads (with higher control), so, just throwing that out there. In case you're interested:

    Linux Tutorial: POSIX Threads
    https://computing.llnl.gov/tutorials/pthreads/

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Running processes
    By pfs in forum Linux Programming
    Replies: 6
    Last Post: 01-01-2009, 07:23 PM
  2. multiple processes
    By f76 in forum C++ Programming
    Replies: 2
    Last Post: 08-04-2004, 02:28 PM
  3. Running simultaneous processes
    By marksw in forum Windows Programming
    Replies: 5
    Last Post: 05-19-2003, 05:07 AM
  4. Multiple Processes maybe?
    By Extol in forum C++ Programming
    Replies: 1
    Last Post: 04-26-2003, 12:44 PM
  5. RE: Find out running processes from command prompt
    By sampatel in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 10-18-2001, 07:15 AM