概念
代码
1. 使用两个管道的客户-服务端程序
#include "unpipc.h"
void client(int, int), server(int, int);
int
main(int argc, char **argv)
{
int pipe1[2], pipe2[2];
pid_t childpid;
Pipe(pipe1); /* create two pipes */
Pipe(pipe2);
if ( (childpid = Fork()) == 0) { /* child */
Close(pipe1[1]);
Close(pipe2[0]);
server(pipe1[0], pipe2[1]);
exit(0);
}
/* 4parent */
Close(pipe1[0]);
Close(pipe2[1]);
client(pipe2[0], pipe1[1]);
Waitpid(childpid, NULL, 0); /* wait for child to terminate */
exit(0);
}
2. 全双工管道
3. popen 和 pclose
popen 函数,它创建一个管道并启动另外一个进程,该进程要么从该管道读出标准输入,要么往该管道写入标准输出。
command是一个shell命令行,
type:
(1)type为 r ,调用进程读进command的标准输出。
(2)type为 w,调用进程写进command的标准输入。
pclose函数关闭有popen创建的标准I/O流,等待其中的命令终止,然后返回shell的终止状态。
#include "unpipc.h"
int
main(int argc, char **argv)
{
size_t n;
char buff[MAXLINE], command[MAXLINE];
FILE *fp;
/* 4read pathname */
Fgets(buff, MAXLINE, stdin);
n = strlen(buff); /* fgets() guarantees null byte at end */
if (buff[n-1] == '\n')
n--; /* delete newline from fgets() */
snprintf(command, sizeof(command), "cat %s", buff);
fp = Popen(command, "r");
/* 4copy from pipe to standard output */
while (Fgets(buff, MAXLINE, fp) != NULL)
Fputs(buff, stdout);
Pclose(fp);
exit(0);
}
4. 使用两个 FIFO 的客户端服务端例子
可将其改成无亲缘关系的客户与服务端
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
#include "unpipc.h"
#define FIFO1 "/tmp/fifo.1"
#define FIFO2 "/tmp/fifo.2"
void client(int, int), server(int, int);
int
main(int argc, char **argv)
{
int readfd, writefd;
pid_t childpid;
/* 4create two FIFOs; OK if they already exist */
if ((mkfifo(FIFO1, FILE_MODE) < 0) && (errno != EEXIST))
err_sys("can't create %s", FIFO1);
if ((mkfifo(FIFO2, FILE_MODE) < 0) && (errno != EEXIST)) {
unlink(FIFO1);
err_sys("can't create %s", FIFO2);
}
if ( (childpid = Fork()) == 0) { /* child */
readfd = Open(FIFO1, O_RDONLY, 0);
writefd = Open(FIFO2, O_WRONLY, 0);
server(readfd, writefd);
exit(0);
}
/* 4parent */
writefd = Open(FIFO1, O_WRONLY, 0);
readfd = Open(FIFO2, O_RDONLY, 0);
client(readfd, writefd);
Waitpid(childpid, NULL, 0); /* wait for child to terminate */
Close(readfd);
Close(writefd);
Unlink(FIFO1);
Unlink(FIFO2);
exit(0);
}