c - 子进程向管道写入内容后无法从管道读取

标签 c linux pipe dup2

我创建了一个函数 exec_in_child,它接受命令参数、管道文件描述符 (fds)、read_flagwrite_flag 作为输入。当write_flag设置为1时,子进程应该复制stdoutfds[1],然后执行命令。当 read_flag 设置为 1 时, child 应将 stdin 复制到 fds[0] 并执行命令。

  • 当我读/写时我必须关闭管道的一端吗 另一端?
  • 下面的代码不起作用。我正在尝试在子进程中执行 /bin/ls ,将标准输出写入管道,然后读取 它在父进程中关闭并打印它。我无法阅读 父进程。
  • 我可以在不关闭其他进程的情况下在同一个进程中读写管道吗?当我要 child 阅读时会出现这种情况 从管道执行,然后写入管道。
#include <stdio.h> /* printf */
#include <stdlib.h> 
#include <string.h> /* strlen, strcpy */

int exec_in_child(char *arguments[], const int temp[], int , int);

int main()
{
    ssize_t bytes_read;
    char *curr_dir = (char *)malloc(500);
    int pipefd[2];

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    char *arguments[] = {"/bin/pwd",0};
    exec_in_child(arguments, pipefd, 0, 1);
    bytes_read = read(pipefd[0], curr_dir, strlen(curr_dir));
    printf("%s = %d\n", "bytes read from pipe" ,(int)bytes_read);
    printf("%s: %s\n","character read from the pipe",curr_dir);
    return 0;
}


int exec_in_child(char * arguments[], const int fds[], int read_flag, int write_flag) {
    pid_t pid;
    pid = fork();
    if (pid < 0) {
        perror("Error: Fork Failed");
    }
    else if (pid == 0){ /*inside the child process */
        if (read_flag == 1) {
            dup2(fds[0], 0);
            perror("Dup2 stdin");
        }
        if (write_flag == 1) {
            dup2(fds[1], 1);
            perror("Dup2 stdout");
        }
        execv(arguments[0], arguments);
        perror("Error in child");
        exit(1);
    } /* if (pid == 0) */
    else {
        while(pid != wait(0));  
    } /* if(pid < 0) */

    return 0;
}

我得到这个结果:

hmwk1-skk2142(test) > ./a.out 
Dup2 stdout: Success
bytes read from pipe = 0
character read from the pipe: 

最佳答案

回答您的问题:

1) 您无需关闭管道的任何一端即可使用另一端。但是,您通常希望关闭不使用的管道的任何一端。这样做的最大原因是只有在关闭所有打开的写入文件描述符时管道才会关闭。

2) 您的代码无法正常工作,因为您未正确使用 strlen()。此函数通过搜索空 (0) 字符来计算字符串的长度。当您 malloc()curr_dir 存储时,您无法保证那里有什么(尽管它通常会被清零,就像在本例中一样)。

因此,您的调用 strlen(curr_dir) 返回零,而 read() 系统调用认为您想要读取最多零字节的数据。将您的读取调用更改为以下内容:

bytes_read = read(pipefd[0], curr_dir, 500);

您的代码将完美运行。

3) 你可以读写任何你有有效文件描述符的管道。单个进程绝对可以读写同一个管道。

关于c - 子进程向管道写入内容后无法从管道读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39682385/

相关文章:

linux - If/then 语句与 awk

linux - 与 Xmonad 一起使用时 Xmobar 不可见

c++ - 将内存保存到文件并加载它而无需解析数据?

console - 可以通过另一个命令管道调试配置吗?

C - 多个 fork 子项的命名管道

c++ - 如何判断ADsOpenObject绑定(bind)的DC?

c - 复制数组的最快方法 - 它有什么问题吗?

pipe - 如何根据同一仪器中先前的复选框结果自动填充 REDCap 复选框

c - 如何从c中的文件中读取多种数据类型

C结构字段分配覆盖另一个字段