我正在尝试检查 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/