首先,对于进程间的通信,信号,管道和共享内存,信号适用于及其微量的信息,管道是进程间通信的大动脉,共享内存是用于大型的软件。
管道式单向的,先进先出,我们先讲无名管道,其中管道编程API是PiPe,API的功能是创建一个无名管道,成功则为数组分配两个文件描述符
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFSIZE 1024
int main(void) {
int pid, fd[2], n;
char buf[BUFSIZE];
if (pipe(fd) < 0) //创建管道
{ printf("pipe error\n"); exit(1); }
if ((pid = fork()) < 0) //创建子进程
{ printf("fork failure\n"); exit(1); }
else if (pid == 0) { //child
close(fd[1]);
while((n = read(fd[0], buf, BUFSIZE))>0) {
write(STDOUT_FILENO, "receive from parent: ", 21);
write(STDOUT_FILENO, buf, n);
}
if (n < 0)
{ printf("read error\n"); exit(1); }
close(fd[0]);
printf("exit child\n");
exit(0);
}
close(fd[0]); //关闭不使用管道读端口
while((n=read(STDIN_FILENO, buf, BUFSIZE)) >0)
write(fd[1], buf, n);
if (n < 0)
{ printf("read error\n"); exit(1); }
close(fd[1]);
pr