/* File: ~liux/public_html/courses/cop4610/examples/simple-pipe.cc
Purpose: Demonstrate how to use pipes to communicate between
parent and child processes
Author: Xiuwen Liu,
On the web:
http://www.cs.fsu.edu/~liux/courses/cop4610/examples/simple-pipe.cc
Compile:
g++ -o simple-pipe simple-pipe.cc
*/
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 512
int main(void)
{
int n, fd[2];
pid_t pid;
char line[MAXLINE];
if (pipe(fd) < 0) {
perror("pipe");
return -1;
}
if ( (pid = fork()) < 0) {
cerr << "Counld not create new process." << endl;
perror("fork");
return -1;
}
else {
if (pid ==0) { /* Child */
close(fd[1]);
n=read(fd[0], line, MAXLINE);
line[n]='\0';
cout << "Child received: " << line;
close(fd[0]);
}
else { /* Parent */
close(fd[0]);
write(fd[1],"Hello, world!\n",strlen("Hello, world!\n"));
close(fd[1]);
}
}
return 0;
}