当前位置: 代码迷 >> 综合 >> Linux 无名管道使用示例
  详细解决方案

Linux 无名管道使用示例

热度:23   发布时间:2023-11-01 08:49:56.0
/*** @file pipe_no_name.c* @author your name (you@domain.com)* @brief 无名管道* 无名管道用于具有亲缘关系的进程间通信* @version 0.1* @date 2021-11-20* * @copyright Copyright (c) 2021* */
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <wait.h>int main()
{int ret;int pipefd[2] = {0};char buffer[64] = {0};//创建无名管道ret = pipe(pipefd);if (ret == -1){perror("pipe");return -1;      }//创建子线程pid_t pid = fork();if (pid == -1){perror("fork");return -1;}if (pid == 0){//childclose(pipefd[1]);int n;//将管道中的小说读出  写入文件中FILE *mortal_fs = fopen("mortal_copy.txt", "w+");if (mortal_fs == NULL){perror("fopen");return -1;}while ((n = read(pipefd[0], buffer, sizeof(buffer))) != 0){fwrite(buffer, 1, n, mortal_fs);//fflush(mortal_fs);//sleep(2);}fclose(mortal_fs);close(pipefd[0]);}else{//parentclose(pipefd[0]);int n;//打开小说文件 把内容写到管道中FILE *mortal_fs = fopen("mortal.txt", "r");if (mortal_fs == NULL){perror("fopen");return -1;}while ((n = fread(buffer, 1, sizeof(buffer), mortal_fs)) != 0){write(pipefd[1], buffer, n);}if (ferror(mortal_fs)){printf("fread fail\n");return -1;}fclose(mortal_fs);close(pipefd[1]);wait(NULL);}
}

示例代码如上,父进程向管道写入数据,子进程从管道中读出数据并保存到文件中。无名管道一般只用于父子进程或兄弟进程(具有亲缘关系)之间通信。