gpt4 book ai didi

c++ - UNIX管道系统读写执行 "ls -la"命令

转载 作者:行者123 更新时间:2023-11-30 05:17:04 24 4
gpt4 key购买 nike

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

最佳答案

首先让我告诉你我从这个问题中得到的解释:

The child will execute exec() and the output of ls -la should be printed by the parent using pipe.

根据这个,我修复了你的代码以提供 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++ - UNIX管道系统读写执行 "ls -la"命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42311231/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com