父进程 通过 fork() 的方式 把管道的读端和写端传递给 子进程
#include <stdio.h>
#include "stdlib.h"
#include "unistd.h"
int main() {
int fd[2];
if (pipe(fd) < 0) {
perror("Fail to create pipe");
exit(EXIT_FAILURE);
}
/**
* create child process (Linux):
* parent_process's pid is child PID
* child_process's pid is 0
*/
pid_t pid = fork();
// start two process from this line
if (pid == -1) {
perror("fork error");
exit(EXIT_FAILURE);
}
// If child process: close read port
if (pid == 0) {
close(fd[0]);
// 管道:传送的是 无格式字节流
write(fd[1], "hello parent", 12);
exit(EXIT_SUCCESS);
}
// parent process: close write port
close(fd[1]);
char buf[20] = {0};
read(fd[0], buf, 20);
printf("receive data = %s\n", buf);
return 0;
}
创建 有名管道
#include "stdio.h"
#include "sys/types.h"
#include "sys/stat.h"
int main() {
int res;
res = mkfifo("../aaa", 0644);
if (res < 0) {
printf("create fifo failure\n");
return -1;
}
printf("create fifo success\n");
return 0;
}
有名管道 写入数据
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "string.h"
int main() {
// use fifo: write
char arr[] = "hello fifo !!!";
int fd = open("../aaa", O_WRONLY);
if (fd == -1) {
printf("open write failure\n");
}
write(fd, arr, strlen(arr));
return 0;
}
有名管道 读出数据
#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
int main() {
// use fifo: read
char buf[30];
int fd = open("../aaa", O_RDONLY);
if (fd == -1) {
printf("open read failure\n");
}
int len = read(fd, buf, sizeof(buf));
write(STDOUT_FILENO, buf, len);
return 0;
}