【问题标题】:UNIX Pipe System with Reading and Writing to Execute "ls -la" CommandUNIX管道系统读写执行“ls -la”命令
【发布时间】:2017-02-18 04:56:56
【问题描述】:

这些是代码说明: 名为 mp2_part6.cpp 的程序使用 fork() 后跟 exec() 启动命令“ls -la”(任何 exec 函数都可以工作)。使用 UNIX 管道系统调用将 ls -la 的输出发送回父级,使用 read() 函数读取它,然后使用 write() 函数将其写入控制台。注意:如果您不关闭和/或重定向正确的文件描述符,管道将不起作用。由您决定哪些是需要的。

这是我目前所拥有的。我不确定为什么它没有打印出正确的输出。

#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>

#include <iostream>

char *cmd1[] = { "/bin/ls -la", 0 };

int main()
{

    int fd[2], nbytes;

    char string[] = "ls -la";
    char readbuffer[80];

    pipe(fd);

    pid_t pid = fork();

    if(pid == 0) { // child writes to pipe

        // open the pipe, call exec here, write output from exec into pipe

        close(fd[0]); // read not needed

        dup(fd[1]);
        close(fd[1]);

        write(fd[1], cmd1[0], strlen(cmd1[0])+1);        

        exit(0);
    }
    else { // parent reads from pipe

        // read output from pipe, write to console

        close(fd[1]); // write not needed

        nbytes = read(fd[0], readbuffer, sizeof(readbuffer));

        std::cout << readbuffer << std::endl;
        execl(readbuffer, (char*)NULL);

        close(fd[0]);
        write(1, readbuffer, nbytes);        
    }

    exit(0);
}

【问题讨论】:

    标签: c++ unix pipe


    【解决方案1】:

    首先让我告诉你我从问题中的解释:

    子进程将执行exec()ls -la 的输出应该由父进程使用管道打印。

    据此,我修复了您的代码以提供ls -la的输出

    #include <stdlib.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <cstring>
    #include <iostream>
    
    char *cmd1[] = { "ls", "-la", NULL }; 
    //for exec each parameter should be a separate string
    
    int main()
    {    
    
        int fd[2], nbytes;
    
        //char string[] = "ls -la"; //unused variable
        char readbuffer[80]; // is a buffer size of 80 enough?
    
        pipe(fd);
    
        pid_t pid = fork();
    
        if(pid == 0) { // child writes to pipe
    
            // open the pipe, call exec here, write output from exec into pipe
    
            dup2(fd[1],1); // stdout goes to fd[1]
            close(fd[0]); // read not needed
    
            execvp(cmd1[0],cmd1); //execute command in child
    
            exit(0);
        }    
        else { // parent reads from pipe
    
            // read output from pipe, write to console
    
            close(fd[1]); // write not needed
    
            //read the output of the child to readbuffer using fd[0]
            nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
    
            //std::cout << readbuffer << std::endl;
            //write also outputs readbuffer
            //output readbuffer to STDOUT
            write(1, readbuffer, nbytes);
        }
    
        exit(0);
    }
    

    【讨论】:

    • 您的解释正确。感谢您的帮助!
    • 赞成票会很好。并感谢您标记为答案。
    猜你喜欢
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2018-02-28
    • 2016-06-18
    • 2013-01-22
    • 1970-01-01
    相关资源
    最近更新 更多