M. Averbach
M. Averbach

Reputation: 125

C Concurrent Processes

I'm trying to do a simple test to see if the processes are running concurrently.

Here is what I have so far:

pid_t pids[argc-1];
pid_t pid;

for(i=1; i<argc; i++)
{
    pid = fork();
    if (pid > 0)
    {
         pids[i-1] = pid;
         printf("process %d created\n", pid);
    }
    else
    {
         exit(0);
    }
}

printf("Main Process\n");

for (i=0; i < argc - 1; i++)
{
     int status;
     wait(pids[i], &status, 0);
     printf("Process %d finished\n", pids[i]);
}

My argc = 4 in this case, so this creates 3 child processes, exactly what I need.

My question is how can I be sure that all processes are running concurrently? I tried calling sleep but that doesn't help, since the processes are created sequentially and each sleep will make them sleep one at a time. I wanted to set the second child process to sleep(1) just to see if the other two processes will print something for example while it is sleeping, but I can't do that inside the for loop.

Also, why is "Main Process" printed only once? Isn't every process, once its done with the for loop, continues to execute until the return statement? I'm confused about this.

Any help would be much appreciated.

Thanks.

Upvotes: 3

Views: 886

Answers (2)

Gilbert
Gilbert

Reputation: 3776

As M. Averbach said, your posted code would exit so fast it would be hard to spot them. But to address your question on how to check if processes are running:

However, if the processes survived a bit longer you could spot them using a basic "ps" command can assure you processes are running:

   ps

If your child processes may have their own children than using a form that shows in tree format can be helpful:

   ps jf

Upvotes: 0

dbush
dbush

Reputation: 223972

The child processes will each return 0 to fork. That means they'll execute the else portion of your if block, which is exit. In other words, each client process exits almost as soon as it starts. The children don't print "Main Process" because they exit before they get there.

If you want the child processes to sleep, call the sleep function in the child portion of the code, i.e. the else block.

For example, you can do something like this:

...
else
{
     printf("in child %d\n", getpid());
     sleep(1);
     printf("in child %d\n", getpid());
     sleep(3);
     exit(0);
}

EDIT:

I'll explain in more detail exactly what happens:

On the first iteration of the for loop, the original process calls fork. This function returns twice: once to the parent where it returns the child's pid, and once to the child where it returns 0.

The parent goes into the if block where it updates its list of pids and goes back to the top of the loop. The child goes to the else part, where it calls exit which ends the child process.

The original parent process is now a the top of the for loop again, and the above repeats 3 more times.

Upvotes: 1

Related Questions