【发布时间】: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);
}
【问题讨论】: