我正在尝试使用/bin/tar -tf
在tar文件上执行execl()
。我希望它读取其内容,并仅通过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],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,&bytes_read,argv);
wait(&status);
// write contents of 'buffer' to the terminal with the
// write(fd,strlen(buffer)) function like so:
// int ch;
// while (1) {
// if ((ch = getchar()) == 27) // Press <Escape> to quit program
// break;
// else
// write(1,strlen(buffer));
// }
return 0;
}
在Linux上以argv[1]
作为压缩包进行编译和执行:
gcc buffer.c -o buffer && ./buffer "$HOME/<your tarball>.tar.gz"
输出显示了tarball的全部内容,而无需诉诸write()
syscall。