2017-02-18 2 views
1

Это инструкции для кода: Программа с именем mp2_part6.cpp, которая запускает команду «ls -la», используя fork(), за которой следует exec() (любая из функций exec будет работать). Используйте системный вызов UNIX для отправки вывода ls -la обратно родительскому, прочитайте его с помощью функции read(), а затем запишите его в консоль с помощью функции write(). Примечание: труба не работает, если вы не закрываете и/или не перенаправляете правильные дескрипторы файлов. Вам решать, какие из них должны быть.Система труб UNIX с чтением и записью для выполнения команды «ls -la»

Это то, что у меня есть до сих пор. Я не уверен, почему он не печатает правильный результат.

#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

Во-первых, позвольте мне сказать вам, что я интерпретировал от вопроса:

Ребенок будет выполнять 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); 
} 
+1

Вы истолковано, что правильно. Спасибо за помощь! –

+0

Проголосовать было бы здорово. И спасибо за маркировку как ответ. –

Смежные вопросы