【问题标题】:Is it possible to use pipe to create a comunication stream between 2 processes without using stderr, stdin or stdout?是否可以在不使用 stderr、stdin 或 stdout 的情况下使用管道在 2 个进程之间创建通信系统?
【发布时间】:2021-06-02 06:49:49
【问题描述】:

就像问题一样。我可以连接 2 个进程(父进程和子进程)通过 pipe() 发送信息但不使用 stdout、stdin 或 stderr 吗?我可以创建一个新的流或缓冲区来使用吗?

编辑:

我的子进程通过 execl() 启动一个新程序,该程序需要通过管道与第一个程序通信,而不使用标准输入和标准输出。

我目前用于通过这些流进行通信的代码如下:

#define READ 0
#define WRITE 1

pid_t
popen2(const char *command, int *infp, int *outfp)
{
int p_stdin[2], p_stdout[2];
pid_t pid;

if (pipe(p_stdin) != 0 || pipe(p_stdout) != 0)
    return -1;

pid = fork();

if (pid < 0)
    return pid;
else if (pid == 0)
{
    close(p_stdin[WRITE]);
    dup2(p_stdin[READ], READ);
    close(p_stdout[READ]);
    dup2(p_stdout[WRITE], 2);

    execl("/bin/bash", "bash", "-c", command, NULL);
    perror("execl");
    exit(1);
}

if (infp == NULL)
    close(p_stdin[WRITE]);
else
{       
    *infp = p_stdin[WRITE];
}

if (outfp == NULL)
    close(p_stdout[READ]);
else
{        
    *outfp = p_stdout[READ];
}

return pid;
}

我目前正在我的子进程中通信从标准输入读取和写入标准输出。如果我想从我创建的不同缓冲区读取和写入以防止由于打印和错误而可能导致的数据损坏怎么办?有可能吗?

【问题讨论】:

  • 您是在问是否可以使用进程间通信工具来做...进程间通信?这就像问是否可以使用锤子将钉子钉入木头。
  • 你是对的,但是我可能错过了我的问题。假设分叉的 pid 使用 execl() 启动一个新程序。通常,我会从父进程与子进程(通过 execl 执行的进程)进行通信,反之亦然,使用标准输入和标准输出,因为两者都有对它的引用。但是,如果我不想使用这些但使用@ani1998ket 下面提供的解决方案之类的解决方案,我如何将对我正在使用的缓冲区的引用而不是标准输入和标准输出传递给第二个程序?
  • 这是一个完全不同的问题。您在问如何访问一个进程从另一个进程创建的管道,而不是从源创建的。
  • 我试图将我的问题编辑得更具体。抱歉,在我因工作日有点筋疲力尽之前提出了不好的问题。

标签: c++ pipe


【解决方案1】:

井管用于您提到的确切目的。

这是 Beej 指南中的一个示例。

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

欲了解更多信息:https://beej.us/guide/bgipc/html/multi/pipes.html#pipesclean

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    相关资源
    最近更新 更多