2015-06-14 61 views
1

的訪問方法,如果當我添加\ n此語句塊現在執行:c + +不ifstatement

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靠近該方法的頂部。

+3

嘗試'「執行命令:%s \ n」'或執行'fflush'。 –

+0

謝謝!這顯示了消息..(做了第一個建議)。它隱藏在某物後面嗎? – ILikeToLearn

+0

文本只是在輸出緩衝區中逗留。現在您已經編輯了代碼,您也必須編輯該說明,否則請刪除該問題。 –

回答