程序間通訊:無名管道
阿新 • • 發佈:2018-11-19
無名管道只能在有親緣關係的程序間通訊
#include <stdio.h> #include <unistd.h> #include <sys/wait.h> #include <errno.h> int main() { int fd[2]; int ret; pid_t pid; char buff[1024] = {0}; ret = pipe(fd);//建立管道 if(!(pid = fork())) { //child close(fd[0]); scanf ("%s",buff); ret = write(fd[1],buff,10); if (ret < 0) { perror("write"); close(fd[1]); return -1; } printf ("sent msg\n"); close(fd[1]); return 0; } //parent close(fd[1]); ret = read(fd[0],buff,10);//阻塞 if(ret < 0) { perror("read"); close(fd[0]); return -1; } printf ("recv msg:%s\n",buff); wait(&pid); close(fd[0]); return 0; }