gpt4 book ai didi

C++ 不访问 if 语句中的方法

转载 作者:行者123 更新时间:2023-11-30 03:52:13 26 4
gpt4 key购买 nike

当我在此处添加\n 时,if 语句 block 现在会执行:

printf("Executing the command: %s\n", cmd);

在此添加之前,它没有命中 getListofProcesses() 方法。原代码如下所示:

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

char* getlistOfProcesses(const char* cmd)
{
FILE* pipe = popen(cmd, "r");
if (!pipe) return (char*)"ERROR";
char buffer[128];
char *result = new char[1024];
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
strcat(result, buffer);
}
pclose(pipe);
return result;
}

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

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

我不确定这是否是由于我的管道完成方式或是否正在访问但我没有注意到,我尝试使用方法顶部附近的 printf 进行检查。

最佳答案

您需要在您的格式字符串中包含一个换行符,或者在您的 printf 语句之后调用 fflush(stdout)。参见 Why does printf not flush after the call unless a newline is in the format string?获取更多信息。

关于C++ 不访问 if 语句中的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30832217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com