Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C (http://www.go4expert.com/forums/c/)
-   -   Need urgent help with C VIM program (http://www.go4expert.com/forums/urgent-help-c-vim-program-t29763/)

LiamSalt 8Aug2013 23:33

Need urgent help with C VIM program
 
I am new to coding in C and even newer to using VIM

I am currently trying to write a code that will store PID numbers of a child after a fork, I have to be able to enter an amount that will be created, so far I have managed to be able to get them to print (which puts me on the right path as far as I am concerned) but I am having issues.

Using the following code:

Code:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
  int prod = atoi(argv[1]);
  int count = 0;
 
  if(argc == 2)
  {
      while(count < prod)
  {
      printf("success\n\n");
      int i;
      i=fork();
      printf("\n");
 
      if(i==0)
      {
        printf("Child printing");
        printf("getpid: %d, getppid: %d \n",getpid(), getppid());
      }

      count++;
      }

  }
  else
  {
      printf("Not enough paramterers");
  }
 
  return 0;

exit(0);
}

while this has some success, it is for some reason creating a 3rd iteration and I can't work out why

The "success" print is more of a marker, but every time I run the program I get this result:
k110-1:~ s029119a$ ./try3.exe 2
success


success



Child printinggetpid: 9335, getppid: 1
success


k110-1:~ s029119a$
Child printinggetpid: 9336, getppid: 1

Child printinggetpid: 9337, getppid: 1
Can anyone offer any advice or tell me what I'm doing wrong, why is it doing this?

xpi0t0s 11Aug2013 23:17

Re: Need urgent help with C VIM program
 
At count=0, try3.exe calls fork() and creates a new process. That new process displays 9335. Remember that you have two identical processes immediately after a fork. After the if, both processes increment count and go to the top of the while. Both processes then have count=1, which is less than prod=2, so display "success", and both then fork again, creating two processes 9336 and 9337. All four processes then increment count, find it to be equal to prod and exit.

Basically what you're doing wrong here is allowing the child processes to continue executing the parent code. Typically the "if(i==0)" block would contain the child code, and that block would end with a call to exit() or some other mechanism to prevent it continuing into the wrong code.

xpi0t0s 11Aug2013 23:21

Re: Need urgent help with C VIM program
 
Before you fix this bug, have a bit of fun by trying a larger parameter, maybe up to 5, but not much bigger unless it's a computer you can freely perform a DoS attack on without implications. See if you can work out why you get the number of processes you do. If you don't see why you shouldn't try a number bigger than 5, first read up on "exponential growth".


All times are GMT +5.5. The time now is 19:37.