【发布时间】:2020-03-03 08:40:01
【问题描述】:
我正在尝试使用 execl() 在 tar 文件上执行 /bin/tar -tf。我希望它读取其内容,并仅在我的 main() 函数中使用 write() 系统调用将其打印到终端屏幕。
我下面的代码以某种方式读取内容并将其同时写入终端,而无需求助于 write() 系统调用。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/wait.h>
int pfd[2];
// Problem 1:
// ERROR : read() function reads and writes to the terminal.
// I would like to write the contents of the 'buffer' variable with the
// write(fd, buffer, strlen(buffer)) syscall to the terminal preferably
// in the main() function.
// Problem 2:
// is the 'status' variable along with the _exit function useful here?
// I am not sure if a pipe is needed?
int show_tar(pid_t *pid, char *buffer, int *bytes_read, char **tar_name)
{
int status = 0;
pipe(pfd);
if ((*pid = fork()) == 0) {
dup2(0, pfd[0]);
execl("/bin/tar", "tar", "-tf", tar_name[1], (char *)NULL);
} else {
close(pfd[1]);
*bytes_read = read(pfd[0], buffer, sizeof(buffer));
wait(NULL);
}
_exit(status);
return status;
}
int main(int argc, char **argv)
{
char buffer[1024];
int bytes_read = 0;
pid_t pid;
int status = show_tar(&pid, buffer, &bytes_read, argv);
wait(&status);
// write contents of 'buffer' to the terminal with the
// write(fd, buffer, strlen(buffer)) function like so:
// int ch;
// while (1) {
// if ((ch = getchar()) == 27) // Press <Escape> to quit program
// break;
// else
// write(1, buffer, strlen(buffer));
// }
return 0;
}
在 Linux 上编译并执行,argv[1] 是 tarball:
gcc buffer.c -o buffer && ./buffer "$HOME/<your tarball>.tar.gz"
输出显示了 tarball 的全部内容,而无需求助于 write() 系统调用。
【问题讨论】:
-
tar写信给stdout。 -
还要确保在
exec*()系列函数之一返回时处理错误情况。它只在错误时返回;无需测试返回值。但是您通常应该至少以非零状态退出;通常,您应该写一条关于标准错误失败的消息,然后退出。是使用exit()还是_exit()可能会令人担忧——使用_exit()通常(通常)没问题,而使用exit()有时是个坏主意。