c、Ubuntu 中奇怪的终端显示故障

问题描述 投票:0回答:1

当我运行第一个代码时,它是“ “在每个打印语句的末尾,它都会给出预期的输出,即

num
==
35

的情况
The generated sequence:
35
106
53
160... 

生成 collatz 序列的代码:

#include<stdlib.h>
#include<stdio.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>

int main(int argc, char* argv[])
{
    int fd[2], fd1[2], num = atoi(argv[1]), id = getpid();
    
    printf("\nRecieved number: %d\n", num);

    if(num > 0)
    {
        printf("The generated sequence: \n");
        
        while(num > 1)
        {   
            pipe(fd);
            pipe(fd1);

            if(fork()) //parent process
            {
                printf("%d \n", num);
                int n;
                close(fd[0]); //closing read end..
                close(fd1[1]); //closing write end..

                write(fd[1], &num, sizeof(num));
                wait(NULL);
                read(fd1[0], &n, sizeof(n));

                num = n;

                close(fd[1]);
                close(fd1[0]);

                if(num == 1) {
                    printf("1\n");
                    exit(0);
                }
            }

            else    //child process
            {
                int n;
                close(fd[1]); //closing write end..
                close(fd1[0]); //closing read end..

                read(fd[0], &n, sizeof(n));

                if(n%2 == 0)
                    n /= 2;
                
                else   
                    n = 3*n+1;

                write(fd1[1], &n, sizeof(n));

                close(fd1[1]);
                close(fd[0]);
                exit(0);
            }
        }
    }

    else {
        printf("\nERROR: number should be positive!!\n");
        exit(1);
    }

    return 0;
}

...但问题是如果我改变打印线

printf("%d \n", num);

printf("%d, ", num);

我的输出会有重复,即

它将打印: 与

n=35

sequence: 35 sequence: 35, 106 sequence: 35, 106, 53 sequence: 35, 106, 53, 160...

虽然在新行上打印解决了重复问题,但我不想在新行上打印序列的每个数字。

c ubuntu virtual-machine
1个回答
6
投票

如果没有换行符,输出将保留在程序的缓冲区中。当程序分叉时,缓冲区与程序的其余部分一起复制。最终,父进程和子进程都会写入更多输出,包括缓冲区中的内容。所以输出会出现多次。

您可以通过刷新缓冲区分叉来消除缓冲区内容的重复。将

fflush(stdout);
紧接在
if (fork())
之前。刷新缓冲区(位于执行进程内部)会将其内容写入流(位于执行进程外部)并清空它。

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