1
The idea of the code is: Give Fork 3 times, that is, from the father create three children (with Count=0,Count=1 and Count=2). The children then, upon returning from the loop will see that their i=0 and will exit the loop. When entering the other condition, they (the children, because i==0), when printing the Count should appear 0,1,2,but is appearing 0,0,0,then give an exec by passing: 1-the path with the name of the executable. 2-The number of the child (0,1,2).
I have the program dad:...
i = 1;
for( count = 0; count < 3; count++) {
if( i != 0 ) {
i = fork();
} else {
break;
}
}
if( i == 0 ) {
printf("%d",count);
char arg[10];
sprintf(arg, "%d", count);
execl("/home/Downloads/filho",arg,NULL);
.... My expected printf ouuput was:
0,1,2
But it’s coming off:
0,0,0
EDIT----- Maybe in the son I’m getting the value wrong: I’m passing like this:
char arg[10];
sprintf(arg, "%d", count);
execl("/home/Downloads/filho",arg,NULL);
And on the executable son:
int n = atoi(argv[1]);
But in this way it generates a problem that does not appear any result in the executable child. and if I put it that way:
int n = atoi(argv[2]);
It prints the results of the executable child, but in the wrong way.
son. c:
int main( int argc, char *argv[] )
{
int n = atoi(argv[2]);
printf("Filho #%d,n);
exit(0);
}
Expected output:
Son #1 Son #2 Son #3
Output when leaving:
Son #0 Son #0 Son #0
How did you define
i
?– stderr
Only with this passage it is difficult to understand what is happening. And as it seems to be doing very weird, it would be good to say what is the purpose of it.
– Maniero
i is initialized with 1;The idea is to give an execl in the child process, passing as parameter the value of the loop in which Fork was given. For example: in the first loop Count=0 then wanted to pass Arg=0 and so on
– felipe alves
http://answall.com/help/mcve
– Maniero
@bigown Edited
– felipe alves
By the passage posted, I can not understand what is happening. Each child will try the
fork
, doi
turn0
and then exit the loop - withcount
equal to1
. The exit then should be1,1,1
, and not0,0,0
.– mgibsonbr
@mgibsonbr I explained what I think the code should do.
– felipe alves
@Sorry, my ignorance, the
fork
doesn’t work the way I thought it would... Still, the expected exit should be1,2,3
- and not0,1,2
- for thecount
of each child process is incremented at least once.– mgibsonbr
Okay, was that right,1,2,3 my mistake too, anyway, :/
– felipe alves
One key is missing in the last if?
– user1084
I tried it on ideone and the result was as expected (out of order, of course). The problem must be somewhere else...
– mgibsonbr
@mgibsonbr I edited with another possible problem
– felipe alves
One thing at a time... Your result in the child process is consistent with what is happening to the
count
. If this problem is solved, I believe the child will function properly.– mgibsonbr