Linux C++ run and communicate with new process

后端 未结 1 1199
生来不讨喜
生来不讨喜 2021-01-25 17:59

I need to make a program that runs a process (my another programm) and can communicate with this process (sending stdin and recieving stdout). I have read about functions like <

相关标签:
1条回答
  • 2021-01-25 18:16

    The interface for POSIX functions C language only. But you can use them in C++.

    Basically:

    #include <unistd.h>
    // Include some other things I forgot. See manpages.
    
    int main()
    {
        // Open two pipes for communication
        // The descriptors will be available to both
        // parent and child.
        int in_fd[2];
        int out_fd[2];
    
        pipe(in_fd);  // For child's stdin
        pipe(out_fd); // For child's stdout
    
        // Fork
        pid_t pid = fork();
    
        if (pid == 0)
        {
            // We're in the child
            close(out_fd[0]);
            dup2(out_fd[1], STDOUT_FILENO);
            close(out_fd[1]);
    
            close(in_fd[1]);
            dup2(in_fd[0], STDIN_FILENO);
            close(in_fd[0]);
    
            // Now, launch your child whichever way you want
            // see eg. man 2 exec for this.
    
            _exit(0); // If you must exit manually, use _exit, not exit.
                      // If you use exec, I think you don't have to. Check manpages.
        }
    
        else if (pid == -1)
            ; // Handle the error with fork
    
        else
        {
            // You're in the parent
            close(out_fd[1]);
            close(in_fd[0]);
    
            // Now you can read child's stdout with out_fd[0]
            // and write to its stdin with in_fd[1].
            // See man 2 read and man 2 write.
    
            // ...
    
            // Wait for the child to terminate (or it becomes a zombie)
            int status
            waitpid(pid, &status, 0);
    
            // see man waitpid for what to do with status
        } 
    }
    

    Don't forget to check error codes (which I did not), and refer to man pages for details. But you see the point: when you open file descriptors (eg. via pipe), they will be available to parent and child. The parent closes one end, the child closes one other end (and redirects the first end).

    Be smart and not afraid of google and man pages.

    0 讨论(0)
提交回复
热议问题