read()从execl命令输出,仅使用write()系统调用将其打印出来

问题描述 投票:-2回答:1

我正在尝试使用/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], 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]作为压缩文件进行编译和执行:

gcc buffer.c -o buffer && ./buffer "$HOME/<your tarball>.tar.gz"

输出显示了压缩包的全部内容,而不必诉诸write() syscall。

我正在尝试使用execl()在tar文件上执行/ bin / tar -tf。我希望它读取其内容,并仅使用write()syscall将其打印到main()函数的终端屏幕上。我的代码...

c fork posix pid
1个回答
1
投票

编辑:这需要大量的工作,并且仍然没有完成,但这应该可以帮助您入门。

© www.soinside.com 2019 - 2024. All rights reserved.