// Sample pipe() program (man pipe) // Creates one children process, and a pipe for them to share data #include #include #include #include #include #define NCHILDS (1) int des[2]; // array of 2 file descriptors int main(int argc, char** argv) { int childpid[NCHILDS]; int i; int j; int fChild = 0; // flag if its a child proc or not int buf; printf("Sample fork() program.\n"); printf("Parent's PID is %d\n", getpid()); // BEFORE FORKING!!! if (pipe(des) == -1) { printf("broken broken broken\n" ); } printf("Forking...\n"); for (i = 0; i < NCHILDS; i++) { childpid[i] = fork(); // Get out of the loop if it's a child process if (childpid[i] == 0) { fChild = 1; break; } } if (fChild == 1) { /* child */ close(des[1]); // child will create random data, and tell its parent for (j = 0; j < 10; j++) { buf = rand(); write(des[0],&buf, sizeof(buf)); sleep(1); } } else { close(des[0]); /* parent */ while (read(des[1], &buf, sizeof(buf)) != 0) { printf("buf = %d\n", buf); } } return 0; }