具有读写功能的UNIX管道系统执行" ls -la"命令

时间:2017-02-18 04:56:56

标签: c++ unix pipe

这些是代码的说明:一个名为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);
}

1 个答案:

答案 0 :(得分: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);
}