无名管道:
#include <stdlib.h>
#include <unistd.h>
#define MAXLINE 80
int main(void)
{
int n;
int fd[2];
pid_t pid;
char line[MAXLINE];
if (pipe(fd) < 0) {
perror("pipe");
exit(1);
}
if ((pid = fork()) < 0) {
perror("fork");
exit(1);
}
if (pid > 0) { /* parent */
close(fd[0]);
write(fd[1], "hello world\n", 12);
wait(NULL);
} else { /* child */
close(fd[1]);
n = read(fd[0], line, MAXLINE);
write(STDOUT_FILENO, line, n);
}
无名管道只能在单个进程间通信。
命名管道:
有三个进程:
mkfifo进程:
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
int main(void)
{
char buf[80];
int fd;
unlink( "zieckey_fifo" );
mkfifo( "zieckey_fifo", 0777 );
}
写进程:
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
int main(void){
int fd;
char s[] = "Hello!\n";
fd = open( "zieckey_fifo", O_WRONLY );
while(1) {
write( fd, s, sizeof(s) );
sleep(1);
}
return 0;
}
读进程:
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<fcntl.h>
#include<stdio.h>
int main(void){
int fd;
char buf[80];
fd = open( "zieckey_fifo", O_RDONLY );
while(1) {
read( fd, buf, sizeof(buf) );
printf("%s\n", buf);
sleep(1);
}
return 0;
}
三个同时进行,可见多进程之间可以传输了。
其实感觉mkfifo进程没啥作用,它可以先结束的,因为它只建了个文件而已。