本文主要是介绍linux 创建并使用 无名管道 / 有名管道,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
父进程 通过 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 lineif (pid == -1) {perror("fork error");exit(EXIT_FAILURE);}// If child process: close read portif (pid == 0) {close(fd[0]);// 管道:传送的是 无格式字节流write(fd[1], "hello parent", 12);exit(EXIT_SUCCESS);}// parent process: close write portclose(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: writechar 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: readchar 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;
}
这篇关于linux 创建并使用 无名管道 / 有名管道的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!