Problem with fork() while reading files

Good evening everyone. I have my finals and I'm facing a problem:

I have a for cycle that is supposed to fork 2 children but somehow it forks only the first one.

What am I doing wrong ?
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
void contare(char *file);
int n,a, status, terminazione;
char *file_in, *file_out;

int main(int argc, char *argv[])
{


int send, pid[MAX],fd, i;
file_in = argv[1];

i=0;
for(i=0; i<2; i++);
{
	pid[i]=fork();
	if ( pid[i] == 0 )
		{
		contare(file_in);
		exit(0);
		}
	if ( pid > 0 )
	{
		printf(" Creato figlio %d \n ", pid[i]);
		for ( i=0; i<2; i++ )
			{
			terminazione = wait(&status);
			if (terminazione == 0)
			printf("Figlio non terminato bene. %d \n", status);
			else
			printf("Figlio %d terminato %d \n", terminazione, status);
			}	
	}	
}




return;
}


void contare(char *file)
{
printf("%c \n\n", a);

int fd = open(file, O_RDONLY);
if ( fd < 0 )
	{
	perror("Failure nell apertura");
	exit(EXIT_FAILURE);
	}
else
	printf("File %s aperto. \n", file_in);
	close(fd);
return;
}


So, the program is pretty simple: I'm supposed to call the program ./program file_name
and its supposed to fork 2 children that will open the same file (argv[1] = file_name ). But as far as I can see I'm missing something because the program forks only one child.

Help ?
Your loop should look something like:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// start children
const int N = 2;
int pids[N];
for (int i = 0; i != N; ++i)
{
    pids[i] = fork();
    if (pids[i] == 0)
    {
        int ret = do_child();
        exit(ret)
    }
}

// join
for (int i = 0; i != N; ++i)
{
    int state = 0;
    waitpid(pids[i], &state, 0);
}
Last edited on
but its the same... anyawy, I tryied to change the code but it still doesn't work.
My code does not create the 2nd child.
Found the problem!
thanks guys!
try changing the inner loop variable to say 'j' rather than i. What i feel is that your main loop does not get executed twice because the value of 'i' already becomes 2 in your inner loop (of parent process).
Last edited on
what was the problem?
Topic archived. No new replies allowed.