1

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

请帮忙。

4

2 回答 2

2

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

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

这将为您提供一个包含 a\r后不跟的字符串\n,因此当您打印它时,光标会回到行首,输出的以下部分将覆盖第一部分。

即使在真正的 unix 上运行而不\r会使事情复杂化,您也不会得到您想要的输出,因为您不允许将 'ed 字符串\n包含在scanf'ed 字符串中并且您没有在%s输出该字符串之后添加一个.

于 2013-06-08T00:52:10.427 回答
1

我会尝试使用getline而不是scanf避免任何特定于平台的问题,例如 Wumpus Q. Wumbley 提到的关于 Windows CRLF 换行符与 Unix/Linux LF 换行符的问题:

char *line = NULL;
getline(&line, NULL, stdin)
printf("the line is:%sand this is the end\n",line);
于 2013-06-08T01:10:50.813 回答