basic forks and pipes

Hi, I am new to Unix & C++ programming, and I am having trouble correctly creating child processes. I want to create a specific number of processes (let's say 5) that all have the main process as their parent. Is this possible?

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
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

int main()
{
	int my_process_id = 0;
	int child_process_id = 0;
	int pipe_file_desc[2];
	
	if(pipe(pipe_file_desc) == -1)
	{	perror("error creating pipe");
		return 1;
	}
	
	int i=0;
	for(i=0; i<5; i++)
		if(my_process_id == 0)
		{
			child_process_id = fork();
			
			if(child_process_id != 0)
			{
				close(pipe_file_desc[0]);
				write(pipe_file_desc[1], &child_process_id,4);
				close(pipe_file_desc[1]);
			}
			else
			{
				close(pipe_file_desc[1]);
				read(pipe_file_desc[0], &my_process_id,4);
				close(pipe_file_desc[0]);
				printf("process %d ID: %d\n",i,my_process_id);
			}
		}
	return 0;
}

What I'm trying to do is have the parent send the child's process id to that specific process and the child will print it. But when I execute this, I get way too many outputs which say 'process ## ID: 0'. Can somebody help me?
I get 16 lines of output and only 1 of them prints an ID # that is not 0
I solved it! I removed the statements which close the pipe. I guess whenever a pipe is completely closed, it becomes useless and you will have to use a different pipe.
Topic archived. No new replies allowed.