【问题标题】:Server/Client comunication through pipe通过管道进行服务器/客户端通信
【发布时间】:2023-12-04 12:02:01
【问题描述】:

我最近开始学习 IPC,但遇到了一些问题。我编写了一个程序,它创建了两个通过管道进行通信的进程,如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>


int main(void)
{
    int pfds[2];
    char buf[30];
    pipe(pfds);
    if (!fork()) 
    {
        printf(" CHILD: writing to the pipe\n");
        write(pfds[1], "test", 5);
        printf(" CHILD: exiting\n");
        exit(0);
    } 
    else 
    {
        printf("PARENT: reading from pipe\n");
        read(pfds[0], buf, 5);
        printf("PARENT: read \"%s\"\n", buf);
        wait(NULL);
    }
    return 0;
}

很抱歉没有处理潜在的错误,为了简单起见,我这样写。

这很好用,但我的问题是:是否有可能有两个程序 - 服务器/客户端(两个单独的可执行文件 - 不是父进程/子进程关系)通过管道进行通信?就像你可以通过 FIFO 一样?

谢谢!

【问题讨论】:

  • mkfifo() 可能会满足您的需求
  • 是的,我知道,我知道如何通过 FIFO 做到这一点,但我想知道是否也可以通过管道做到这一点。

标签: c client-server ipc communication pipe


【解决方案1】:

一个普通的管道只能连接两个相关的进程。它由一个进程创建,并在最后一个进程关闭时消失。

要在两个独立的进程之间进行通信,您必须使用命名管道 (FIFO)。

【讨论】:

  • 谢谢,我需要确认 :)
最近更新 更多