if statement - C++ not accessing method in ifstatement -
the if statement block executes when add \n here:
printf("executing command: %s\n", cmd);
before addition, didn't hit getlistofprocesses() method. original code shown below:
#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 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; }
i'm not sure if due way pipes done or if being accessed , don't notice, tried check printf near top of method.
you need include newline in format string, or call fflush(stdout)
after printf statement. see why printf not flush after call unless newline in format string? more information.
Comments
Post a Comment