
the head file of the pipe() function is <unistd.h> :
#include <unistd.h>
int pipe(int fd[2]);
1. the use of pipe in inter-process communications
Pipe is often used for communications between processes which have genetic relationship with each other. the following is an example given by UNP(II):
#include <unistd.h> /*pipe() && fork() & write() & read() & STDOOUT_FILENO*/
#include <sys/types.h> /* pid_t ssize_t*/
#include <sys/wait.h> /* waitpid() */
#include <stdio.h> /*fgets(), stdin*/
#include <string.h> /*strlen*/
#define BUFFERSIZE 20
void client(int readfd, int writefd);
void server(int readfd, int writefd);
int main(int argc, char *argv[]) {
int pipe1[2], pipe2[2];
pid_t child_pid;
pipe(pipe1); /* create two pipes */
pipe(pipe2);
if( (child_pid = fork()) == 0) { /*child process for server */
close(pipe1[1]); /* close write fd*/
close(pipe2[0]); /* close read fd */
server(pipe1[0], pipe2[1]); /*read from pipe1[0], and write to pipe2[1]*/
exit();
}
close(pipe1[1]);
close(pipe2[0]);
client(pipe1[1], pipe2[0]); /*write to pipe1[0], and read from pipe2[1]*/
waitpid(child_pid, NULL, 0);
}
void client(int readfd, int writefd) {
size_t len;
ssize_t n;
char buff[BUFFERSIZE];
fgets(buff, BUFFERSIZE, stdin);
len = strlen(buff);
if (buff[len-1] == 'n'){
len--;
}
write(writefd, buff, len);
while ((n = read(readfd, buff, BUFFERSIZE)) > 0) {
write(writefd, buff, n);
}
}
void server(int readfd, int writefd) {
size_t len;
ssize_t n;
int fd;
char buff[BUFFERSIZE+1];
if (n = read(readfd, buff, BUFFERSIZE) == 0) {
printf("server read error!");
eixt(1);
}
buff[n] = '




近期评论