C++ popen command without console

后端 未结 4 1174
借酒劲吻你
借酒劲吻你 2020-12-20 17:20

when I use popen to get the output of a command, say dir, it will prompt out a console.

however, can I get the output of a command without the appearance of the cons

4条回答
  •  离开以前
    2020-12-20 17:36

    With POSIX it should be something like this:

    //Create the pipe.
    int lsOutPipe[2];
    pipe(lsOutPipe);
    
    //Fork to two processes.
    pid_t lsPid=fork();
    
    //Check if I'm the child or parent.
    if ( 0 == lsPid )
    {//I'm the child.
      //Close the read end of the pipe.
      close(lsOutPipe[0]);
    
      //Make the pipe be my stdout.
      dup2(lsOutPipe[1],STDOUT_FILENO);
    
      //Replace my self with ls (using one of the exec() functions):
      exec("ls"....);//This never returns.  
    } // if
    
    //I'm the parent.
    //Close the read side of the pipe.
    close(lsOutPipe[1]);
    
    //Read stuff from ls:
    char buffer[1024];
    int bytesRead;
    do
    {
      bytesRead = read(emacsInPipe[0], buffer, 1024);
    
      // Do something with the read information.
      if (bytesRead > 0) printf(buffer, bytesRead);
    } while (bytesRead > 0);
    

    You should off course check return values etc...

提交回复
热议问题