c - 当我尝试使用 write (man 2 write) 函数时,为什么这段代码会卡住?

标签 c pipe unistd.h

我正在尝试编写测试,其中应从文件描述符读取一些数据,因此我使用 dup 和管道函数来检查这一点。

 int main()
{
    char    *line;
    int     out;
    int     p[2];
    char    *str;
    int     len = 50;

    str = (char *)malloc(235436);
    for (int i = 0; i < 235436; ++i)
    {
        str[i]='h';
    }
    out = dup(1);
    pipe(p);
    dup2(p[1], 1);

    write(1, str, strlen(str)); //freezes there. malloc alocates memory, i've checked this with debuger
    close(p[1]);
    dup2(out, 1);
    get_next_line(p[0], &line);


}

由于某种原因,这段代码可以完美地工作,尽管它的作用都是一样的。

str = (char *)malloc(1000 * 1000);
    *str = '\0';
    while (len--)
        strcat(str, "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur in leo dignissim, gravida leo id, imperdiet urna. Aliquam magna nunc, maximus quis eleifend et, scelerisque non dolor. Suspendisse augue augue, tempus");
    out = dup(1);
    pipe(p);
    dup2(p[1], 1);

    if (str)
        write(1, str, strlen(str));
    close(p[1]);
    dup2(out, 1);
    get_next_line(p[0], &line);

最佳答案

(假设您解决了 strlen 问题 - 即 write(1, str, 235436))

您正在向管道写入数据。该管道未被读取。因此write将会被阻塞。

从管道中读取一些内容。

关于c - 当我尝试使用 write (man 2 write) 函数时,为什么这段代码会卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54256724/

相关文章:

R中的读写管道()通信

C - 函数内的动态分配/重定位

c - 为什么这个数组的第一个成员被 MPI_Recv 覆盖了?

c - 问 : Read line to line from file and send to child process with pipes

c - 使用 NULL 强制结束可变函数参数

c - 警告 : implicit declaration of function 'daemon'

c - open() 和 read() 系统调用...程序未执行

c - 大文件的LZW编码

c++ - Eclipse CDT 调试(步骤过滤器/避免库代码)

unix - 猫文件| ... vs ... <文件