HELP!
Aug 8, 2013 at 5:01pm UTC
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
1 #include <stdio.h>
2 #include <sys/types.h>
3 #include <unistd.h>
4 #include <stdlib.h>
5
7 int main(int argc, char *argv[])
8 {
9 int prod = atoi(argv[1]);
10 int count = 0;
11
12 if (argc == 2)
13 {
14 while (count < prod)
15 {
16 printf("success\n\n" );
18 int i;
19 i=fork();
20 printf("\n" );
21
22 if (i==0)
23 {
24 printf("Child printing" );
25 printf("getpid: %d, getppid: %d
\n" ,getpid(), getppid());
26 }
27
28 count++;
29 }
30
31 }
32 else
33 {
34 printf("Not enough paramterers" );
35 }
36
37 return 0;
38
39 exit(0);
40 }
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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?
Aug 8, 2013 at 5:06pm UTC
try ++count
Aug 8, 2013 at 5:08pm UTC
instead of count++?
Aug 8, 2013 at 5:09pm UTC
yeah its the only thing that might be causing it i can see
Aug 8, 2013 at 5:10pm UTC
Didn't work, actually added results :/
Aug 8, 2013 at 5:14pm UTC
wait sorry my mistake... its because fork is calling the program multiple times. i would make the condition while(count < prod - 1)
Aug 8, 2013 at 5:21pm UTC
That 1 less than the required, I am so confused
Aug 8, 2013 at 5:46pm UTC
Sorry that produces a result with one less iteration that the request
Aug 8, 2013 at 6:35pm UTC
fixed it I was missing a return value statement.
Topic archived. No new replies allowed.