【C语言】【unix c】如何使用管道实现两个进程间的通信

xiaoxiao2021-02-28  55

如何使用管道实现两个进程间的通信: 步骤: 1、父进程创建管道 2、父进程创建子进程(子进程继承了父进程的文件描述符号) 3、考虑父进程负责的工作(这里设置为写) a、关闭读端 b、通过管道的写端文件描述符,写数据到管道空间 c、阻塞等待子进程的结束,子进程结束的时候,收尸 4、考虑子进程负责的工作 a、关闭写端 b、从管道中读取数据 c、将读取到的数据显示到显示器 d、结束进程 举例:(pipe.c) 程序: #include <stdio.h> #include <sys/wait.h> #include <stdlib.h> #include <unistd.h> #include <string.h> int main(void) { //1、创建管道 int fd[2]; int pc = pipe(fd); char buf[128]; int r; char *msg = "this is a test\n"; if(pc == -1) { perror("pipe"); return -1; } //2、创建进程 pid_t pid = fork(); if(pid == -1) { perror("fock"); return -1; } if(pid == 0) { //4、考虑子进程的工作 //关闭写端 close(fd[1]); //从管道读取数据 r = read(fd[0], buf, 128); //输出到显示器 write(1, buf, r); //子进程退出 exit(0); } else { //3、考虑父进程的工作 //关闭读端,关闭0号描述符 close(fd[0]); //向管道写数据 write(fd[1], msg, strlen(msg)); //等待子进程结束 wait(NULL); } return 0; } 运行: 命令: tarena@ubuntu:~/day/day32$ a.out 结果: this is a test
转载请注明原文地址: https://www.6miu.com/read-58881.html

最新回复(0)