这些是代码的指令:名为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);
}

最佳答案

首先,让我告诉您我对这个问题的解释:



据此,我修复了您的代码以提供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);
}

关于c++ - 具有执行 “ls -la”命令的读写功能的UNIX管道系统,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42311231/

10-11 16:19