Hi everyone!
I am writing a program in C under UNIX, the task basically is this:
create three processes, two write down the pipe and one that reads from the pipe. The first child process writes the first 20 odd integers, and the second child process writes the first 20 even integers. Make the reading process (the third child process) print any messages it receives on its standard output. Find out a solution and modify the program to guarantee the reader can get the numbers in numerical order.
After executing some code I have, I get a Segmentation fault.
Can anyone give me a hint why am i getting this??
I know it is something about unallocated memory, but i'm so new to all these multiprocesses and pipes, and not very clear about them.
Please, help!
Here is my code:
I am writing a program in C under UNIX, the task basically is this:
create three processes, two write down the pipe and one that reads from the pipe. The first child process writes the first 20 odd integers, and the second child process writes the first 20 even integers. Make the reading process (the third child process) print any messages it receives on its standard output. Find out a solution and modify the program to guarantee the reader can get the numbers in numerical order.
After executing some code I have, I get a Segmentation fault.
Can anyone give me a hint why am i getting this??
I know it is something about unallocated memory, but i'm so new to all these multiprocesses and pipes, and not very clear about them.
Please, help!
Here is my code:
Code:
#include <stdio.h>
main()
{
int buff;
int odd =1;
int count =1;
int flag =0;
int even =2;
int p[2], pid1, pid2, pid3;
pipe(p);
pid1 = fork();
pid2 = fork();
pid3 = fork();
while(count < 21)
{
if (( pid1 = 0 )&&( flag == 0 ))
{
printf("Odd number: \n");
write(p[1], odd);
odd = odd + 1;
flag = 1;
}
else
{
sleep(1);
read(p[0], buff);
printf("Number read: %s\n", buff);
}
if (( pid2 = 0 )&&( flag == 1 ))
{
printf("Even number: \n");
write(p[1], even);
even = even + 2;
flag = 0;
}
else
{
sleep(1);
read(p[0], buff);
printf("Number read: %s\n", buff);
}
count = count + 1;
}
}
Comment