“fork()"之后的printf异常 [英] printf anomaly after "fork()"

查看:37
本文介绍了“fork()"之后的printf异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

操作系统:Linux,语言:纯C

OS: Linux, Language: pure C

我正在学习一般的 C 编程,在特殊情况下学习 UNIX 下的 C 编程.

I'm moving forward in learning C programming in general, and C programming under UNIX in a special case.

在使用 fork() 调用后,我检测到 printf() 函数的一个奇怪的(对我来说)行为.

I detected a strange (for me) behaviour of the printf() function after using a fork() call.

代码

#include <stdio.h>
#include <system.h>

int main()
{
    int pid;
    printf( "Hello, my pid is %d", getpid() );

    pid = fork();
    if( pid == 0 )
    {
            printf( "
I was forked! :D" );
            sleep( 3 );
    }
    else
    {
            waitpid( pid, NULL, 0 );
            printf( "
%d was forked!", pid );
    }
    return 0;
}

输出

Hello, my pid is 1111
I was forked! :DHello, my pid is 1111
2222 was forked!

为什么第二个Hello"字符串出现在孩子的输出中?

Why did the second "Hello" string occur in the child's output?

是的,这正是父启动时打印的,带有父的pid.

Yes, it is exactly what the parent printed when it started, with the parent's pid.

但是!如果我们在每个字符串的末尾放置一个 字符,我们会得到预期的输出:

But! If we place a character at the end of each string we get the expected output:

#include <stdio.h>
#include <system.h>

int main()
{
    int pid;
    printf( "Hello, my pid is %d
", getpid() ); // SIC!!

    pid = fork();
    if( pid == 0 )
    {
            printf( "I was forked! :D" ); // removed the '
', no matter
            sleep( 3 );
    }
    else
    {
            waitpid( pid, NULL, 0 );
            printf( "
%d was forked!", pid );
    }
    return 0;
}

输出:

Hello, my pid is 1111
I was forked! :D
2222 was forked!

为什么会这样?这是正确的行为,还是错误?

Why does it happen? Is it correct behaviour, or is it a bug?

推荐答案

我注意到 是一个非标准的标题;我用 <unistd.h> 替换了它,代码编译得很干净.

I note that <system.h> is a non-standard header; I replaced it with <unistd.h> and the code compiled cleanly.

当你的程序输出到终端(屏幕)时,它是行缓冲的.当程序的输出进入管道时,它被完全缓冲.您可以通过标准 C 函数 setvbuf()_IOFBF(全缓冲)、_IOLBF(行缓冲)和 _IONBF(无缓冲)模式.

When the output of your program is going to a terminal (screen), it is line buffered. When the output of your program goes to a pipe, it is fully buffered. You can control the buffering mode by the Standard C function setvbuf() and the _IOFBF (full buffering), _IOLBF (line buffering) and _IONBF (no buffering) modes.

您可以通过将程序的输出通过管道传送到例如 cat 来在修改后的程序中演示这一点.即使在 printf() 字符串末尾有换行符,您也会看到双重信息.如果直接发送到终端,那么你只会看到一大堆信息.

You could demonstrate this in your revised program by piping the output of your program to, say, cat. Even with the newlines at the end of the printf() strings, you would see the double information. If you send it direct to the terminal, then you will see just the one lot of information.

这个故事的寓意是要小心调用 fflush(0); 在 fork 之前清空所有 I/O 缓冲区.

The moral of the story is to be careful to call fflush(0); to empty all I/O buffers before forking.

按要求进行逐行分析(删除大括号等 - 标记编辑器删除前导空格):

Line-by-line analysis, as requested (braces etc removed - and leading spaces removed by markup editor):

  1. printf( "你好,我的 pid 是 %d", getpid() );
  2. pid = fork();
  3. if(pid == 0)
  4. printf( " 我被分叉了!:D");
  5. sleep( 3 );
  6. else
  7. waitpid(pid, NULL, 0);
  8. printf( " %d 被分叉了!", pid );
  1. printf( "Hello, my pid is %d", getpid() );
  2. pid = fork();
  3. if( pid == 0 )
  4. printf( " I was forked! :D" );
  5. sleep( 3 );
  6. else
  7. waitpid( pid, NULL, 0 );
  8. printf( " %d was forked!", pid );

分析:

  1. 将你好,我的 pid 是 1234"复制到标准输出的缓冲区中.由于末尾没有换行符,并且输出以行缓冲模式(或全缓冲模式)运行,因此终端上没有任何显示.
  2. 为我们提供了两个独立的进程,标准输出缓冲区中的材料完全相同.
  3. 孩子有 pid == 0 并执行第 4 行和第 5 行;父进程的 pid 有一个非零值(两个进程之间的少数区别之一 - getpid()getppid() 的返回值)代码>还有两个).
  4. 向孩子的输出缓冲区添加一个换行符和我被分叉了!:D".第一行输出出现在终端上;其余部分保存在缓冲区中,因为输出是行缓冲的.
  5. 一切都停止了 3 秒.在此之后,子进程通过 main 末尾的 return 正常退出.此时,stdout 缓冲区中的剩余数据将被刷新.由于没有换行符,这会将输出位置留在行尾.
  6. 家长来了.
  7. 父母等待孩子死亡.
  8. 父级添加了一个换行符,1345 被分叉了!"到输出缓冲区.在子代生成的不完整行之后,换行符将Hello"消息刷新到输出.
  1. Copies "Hello, my pid is 1234" into the buffer for standard output. Because there is no newline at the end and the output is running in line-buffered mode (or full-buffered mode), nothing appears on the terminal.
  2. Gives us two separate processes, with exactly the same material in the stdout buffer.
  3. The child has pid == 0 and executes lines 4 and 5; the parent has a non-zero value for pid (one of the few differences between the two processes - return values from getpid() and getppid() are two more).
  4. Adds a newline and "I was forked! :D" to the output buffer of the child. The first line of output appears on the terminal; the rest is held in the buffer since the output is line buffered.
  5. Everything halts for 3 seconds. After this, the child exits normally through the return at the end of main. At that point, the residual data in the stdout buffer is flushed. This leaves the output position at the end of a line since there is no newline.
  6. The parent comes here.
  7. The parent waits for the child to finish dying.
  8. The parent adds a newline and "1345 was forked!" to the output buffer. The newline flushes the 'Hello' message to the output, after the incomplete line generated by the child.

parent现在通过main末尾的return正常退出,清空剩余数据;由于最后还没有换行,光标位置在感叹号之后,shell提示出现在同一行.

The parent now exits normally through the return at the end of main, and the residual data is flushed; since there still isn't a newline at the end, the cursor position is after the exclamation mark, and the shell prompt appears on the same line.

我看到的是:

Osiris-2 JL: ./xx
Hello, my pid is 37290
I was forked! :DHello, my pid is 37290
37291 was forked!Osiris-2 JL: 
Osiris-2 JL: 

PID 编号不同 - 但整体外观清晰.在 printf() 语句的末尾添加换行符(这很快成为标准做法)会大大改变输出:

The PID numbers are different - but the overall appearance is clear. Adding newlines to the end of the printf() statements (which becomes standard practice very quickly) alters the output a lot:

#include <stdio.h>
#include <unistd.h>

int main()
{
    int pid;
    printf( "Hello, my pid is %d
", getpid() );

    pid = fork();
    if( pid == 0 )
        printf( "I was forked! :D %d
", getpid() );
    else
    {
        waitpid( pid, NULL, 0 );
        printf( "%d was forked!
", pid );
    }
    return 0;
}

我现在得到:

Osiris-2 JL: ./xx
Hello, my pid is 37589
I was forked! :D 37590
37590 was forked!
Osiris-2 JL: ./xx | cat
Hello, my pid is 37594
I was forked! :D 37596
Hello, my pid is 37594
37596 was forked!
Osiris-2 JL:

请注意,当输出到达终端时,它是行缓冲的,因此Hello"行出现在 fork() 之前,并且只有一个副本.当输出通过管道传送到 cat 时,它是完全缓冲的,所以 fork() 之前什么都没有出现,并且两个进程在缓冲区中都有Hello"行脸红了.

Notice that when the output goes to the terminal, it is line-buffered, so the 'Hello' line appears before the fork() and there was just the one copy. When the output is piped to cat, it is fully-buffered, so nothing appears before the fork() and both processes have the 'Hello' line in the buffer to be flushed.

这篇关于“fork()"之后的printf异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆