我正在尝试检查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个管道:两个在父进程中,两个在子进程中。

在分叉之前创建管道!然后派生,然后检查您是在父进程中还是在子进程中。

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

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

10-12 00:32
查看更多