无名管道只能在有亲缘关系的进程间通讯 

#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;
}

 

相关文章:

  • 2021-10-12
  • 2022-01-19
  • 2021-06-11
  • 2021-05-16
  • 2021-09-14
  • 2021-09-22
  • 2021-09-29
  • 2022-12-23
猜你喜欢
  • 2021-12-14
  • 2021-05-15
  • 2021-05-18
  • 2021-04-22
  • 2021-03-31
  • 2021-08-30
  • 2021-07-19
相关资源
相似解决方案