c - 管道后打印顺序困惑

标签 c pipe

childc.exe 程序是这样的:

#include<stdio.h>
#include<windows.h>
int main()
{
    printf("this is apple pie\n");
    return 0;
}

主程序调用fork(),然后调用execl()来处理childc.exe。代码如下:

#include <stdio.h>
#include<windows.h>
#include<unistd.h>
int main()
{
    int fd[2];
    if(pipe(fd)==-1)
    {
        printf("pipe failed\n");
        exit(1);
    }
    pid_t pid=fork();
    if(!pid)
    {
        dup2(fd[1],1);
        close(fd[0]);
        execl("childc.exe","childc.exe",NULL);
    }
    dup2(fd[0],0);
    close(fd[1]);
    char line[100];
    scanf("%[^\n]",line);
    printf("the line is:%sand this is the end\n",line);
    return 0;
}

我希望得到这样的输出:

the line is: this is apple pie
and this is the end

但实际输出是:

and this is the end apple pie

请帮忙。

最佳答案

看起来像 unix 代码,除了 .exe<windows.h> .在 cygwin 中运行这个?

问题似乎是子进程使用 Windows 样式的 CRLF 行终止符打印其输出,而父进程的 scanf正在阅读 LF 但不包括它,因为你说 %[^\n] .

这会得到一个包含 \r 的字符串后面没有 \n , 所以当你打印它时,光标会回到行首,输出的后续部分会覆盖第一部分。

即使在没有 \r 的真实 unix 上运行使事情复杂化,你不会得到你想要的输出,因为你不允许 \n包含在 scanf 中'ed 字符串,但您没有在 %s 之后添加一个输出那个字符串。

关于c - 管道后打印顺序困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16994729/

相关文章:

C realloc 段错误

C struct object Stack - 常量表达式中不允许函数调用(错误)

r - 使用管道运算符 "%>%"using::in R

c - 将输出从文件重定向到三个正在运行的线程

python - 在 Python 3.7 中使用和重叠命名管道

c - c中一个未初始化的指针指向的目的地是如何确定的?

c - Linux 中断与轮询

java - 与另一个进程的标准输入通信时出现意外结果

c++ - 父进程不读取表单管道

c - 循环输入行并调用 C 中的函数?