1. 無名管道(PIPE)
#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) {
close(fd[0]);
write(fd[1], "hello world\n", 12);
wait(NULL);
}
else {
close(fd[1]);
n = read(fd[0], line, MAXLINE);
write(STDOUT_FILENO, line, n);
}
return 0;
}
2. 有名管道(FIFO)
發送方:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#define FIFO "./myfifo"
int main(int argc, char **argv){
if(access(FIFO, F_OK)){
mkfifo(FIFO, 0644);
}
int fifo = open(FIFO, O_WRONLY);
char msg[20];
while(1){
bzero(msg, 20);
fgets(msg, 20, stdin);
int n = write(fifo, msg, strlen(msg));
}
return 0;
接收方:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#define FIFO "./myfifo"
int main(int argc, char **argv){
if(access(FIFO, F_OK)){
mkfifo(FIFO, 0644);
}
int fifo = open(FIFO, O_RDONLY);
char msg[20];
bzero(msg, 20);
while(1){
read(fifo, msg, 20);
printf("from FIFO: %s", msg);
}
return 0;
}