At a course the teacher gave us some code (on the chalk board) but he has horrible hand writing, and I can’t make a few parts out. Also new at both pipe and fork so that doesn’t help.
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
void main () {
int a[] = {1,2,3,4}, f[2]; // ok so we initialize an array and a "pipe folder" (pipefd in manual) ?
pipe (f); // not 100% sure what this does ?
if (fork () == 0) { // if child
close (f[0]); // close pipe read-end
a[0] += a[1];
write (f[1], &a[0], sizeof (int)) // fixed
close (f[1]); // close pipe write-end
exit(0); // closes child and sends status update to parent ?
}
else { // if parent
close (f[1]) // close write-end of pipe
a[2]+=a[3];
read (f[0], &a, sizeof(int)) // fixed
wait (0); // waits for child to ... close ? or just finish ? or is it the same thing
a[0]+= a[2]; close (f[0]);
printf ("%d\n, "a[0]);
}
}
Does the child and parent go in some particular order. I’m guessing parent waits for child to close, if close (f[1]) returns no error it continues ? (btw what does the “0” stand for in wait(0)) and only then continues ?
What am I misunderstanding? am I getting something right ?
I thought I should mention that I did some research using man but I find it tremendously confusing. As far as I am concerned they are for users who already either know what they are doing but forgot some details (like what to include and what -p does) or people who have a more than basic understanding.
pipecreates two file descriptors. One you write to and the other you read from. What you write into one, you can read from the other. File descriptors in UNIX are integers (int).sizeofi.e.sizeof(int). The compile will give the right value for the number of bytes that store andintwait(0)waits for the child to terminate.