C++ 字符数组未通过管道直接读取

标签 c++ arrays pipe

我正在尝试检查 cmd 变量是否设置为“LISTALL”,但当我尝试将其打印出来时却没有设置。

#include <stdio.h>
#include <unistd.h>
#include <cstring>
#include <stdlib.h>
#include <iostream>
#include <sys/wait.h>

int main(int argc, char **argv)
{   
    pid_t cPid = fork();
    int P2C[2];
    int C2P[2];
    pipe(P2C);
    pipe(C2P);

    char cmd[50];
    char* listOfProcesses = new char[1024];

    if (cPid == 0)
    {
        ...
        read(P2C[0], cmd, 50);  
        printf("%s\n", cmd);
        if(strcmp(cmd,"LISTALL") == 0)
        {
            //printf("Executing the command: %s", cmd);
            write(C2P[1], getlistOfProcesses("ps -ax -o pid,cmd"), 1024);
            ...
        }
    }
    else if (cPid > 0)
    {
        ...
        write(P2C[1], "LISTALL", 50);
        wait(NULL);
        read(C2P[0], listOfProcesses,1024);
        ...
    }
    else
    {
        // fork failed
        printf("Forking failed!\n");
        exit(1);
    }
    return 0;
}

我从中得到的是一个迷你框符号,顶部为 00,底部为 01 或 02。我尝试将符号粘贴到此处,但它没有显示。

最佳答案

您创建了 4 个管道:两个在父进程中,两个在子进程中。

在 fork 之前创建管道!然后fork,然后检查你是在父进程还是在子进程。

这样你就只有两个管道,两个进程都知道这些管道并且可以通过读取或写入管道的适当文件描述符来进行通信。

关于C++ 字符数组未通过管道直接读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30831223/

相关文章:

c++ - 将静态库转换为DLL导致main之前的访问冲突

JavaScript 减去零更改结果

python - 如何将 stdin 直接输入 python 并像 grep 一样解析?

c++ - 如何在 Linux 机器上链接一个静态库文件

c++ - 这不是尾递归吗? (堆栈溢出错误)

c++ - 从 HKEY 转换为字符串,C++

arrays - tensorflow 创建不同长度的掩码

javascript - 在 html 中显示嵌套的 json 对象

python - Python 中的选择和管道问题

linux - 从 radio 流中保存最喜欢的轨道