"fork ()"후 printf 이상
OS : Linux, 언어 : pure C
저는 일반적으로 C 프로그래밍을 배우고 특별한 경우에는 UNIX에서 C 프로그래밍을 배우고 있습니다.
호출 printf()
을 사용한 후 함수 의 이상한 동작을 감지했습니다 fork()
.
암호
#include <stdio.h>
#include <system.h>
int main()
{
int pid;
printf( "Hello, my pid is %d", getpid() );
pid = fork();
if( pid == 0 )
{
printf( "\nI was forked! :D" );
sleep( 3 );
}
else
{
waitpid( pid, NULL, 0 );
printf( "\n%d was forked!", pid );
}
return 0;
}
산출
Hello, my pid is 1111
I was forked! :DHello, my pid is 1111
2222 was forked!
두 번째 "Hello"문자열이 자식의 출력에 나타나는 이유는 무엇입니까?
예, 부모가 시작했을 때 부모의 pid
.
그러나! \n
각 문자열 끝에 문자를 배치 하면 예상되는 출력을 얻습니다.
#include <stdio.h>
#include <system.h>
int main()
{
int pid;
printf( "Hello, my pid is %d\n", getpid() ); // SIC!!
pid = fork();
if( pid == 0 )
{
printf( "I was forked! :D" ); // removed the '\n', no matter
sleep( 3 );
}
else
{
waitpid( pid, NULL, 0 );
printf( "\n%d was forked!", pid );
}
return 0;
}
출력 :
Hello, my pid is 1111
I was forked! :D
2222 was forked!
왜 발생합니까? 올바른 동작입니까, 아니면 버그입니까?
<system.h>
비표준 헤더 라는 점에 유의합니다 . 나는 그것을로 <unistd.h>
바꾸고 코드를 깔끔하게 컴파일했습니다.
프로그램의 출력이 터미널 (화면)로 이동하면 라인 버퍼링됩니다. 프로그램의 출력이 파이프로 이동하면 완전히 버퍼링됩니다. 표준 C 기능 setvbuf()
과 _IOFBF
(전체 버퍼링), _IOLBF
(라인 버퍼링) 및 _IONBF
(버퍼링 없음) 모드로 버퍼링 모드를 제어 할 수 있습니다 .
프로그램의 출력을 예를 들어 cat
. printf()
문자열 끝에 줄 바꿈이 있어도 이중 정보를 볼 수 있습니다. 터미널로 직접 보내면 많은 정보 만 볼 수 있습니다.
이야기의 교훈은 fflush(0);
포크하기 전에 모든 I / O 버퍼를 비우 도록 호출 하도록 주의하는 것 입니다.
요청 된대로 줄 단위 분석 (중괄호 등이 제거되고 마크 업 편집기에서 선행 공백이 제거됨) :
printf( "Hello, my pid is %d", getpid() );
pid = fork();
if( pid == 0 )
printf( "\nI was forked! :D" );
sleep( 3 );
else
waitpid( pid, NULL, 0 );
printf( "\n%d was forked!", pid );
분석:
- "Hello, my pid is 1234"를 표준 출력용 버퍼에 복사합니다. 끝에 줄 바꿈이없고 출력이 줄 버퍼 모드 (또는 전체 버퍼 모드)로 실행되기 때문에 터미널에 아무것도 나타나지 않습니다.
- stdout 버퍼에서 정확히 동일한 재료를 사용하여 두 개의 개별 프로세스를 제공합니다.
- 아이는
pid == 0
라인 4와 5를 가지고 있고 실행합니다. 부모는 0이 아닌 값을가집니다pid
(두 프로세스 간의 몇 가지 차이점 중 하나-반환 값getpid()
과getppid()
두 개 더 있음). - 줄 바꿈과 "I was forked! : D"를 자식의 출력 버퍼에 추가합니다. 출력의 첫 번째 줄이 터미널에 나타납니다. 나머지는 출력이 라인 버퍼링되기 때문에 버퍼에 보관됩니다.
- 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.
- The parent comes here.
- The parent waits for the child to finish dying.
- 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.
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.
What I see is:
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:
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\n", getpid() );
pid = fork();
if( pid == 0 )
printf( "I was forked! :D %d\n", getpid() );
else
{
waitpid( pid, NULL, 0 );
printf( "%d was forked!\n", pid );
}
return 0;
}
I now get:
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:
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.
The reason why is that without the \n
at the end of the format string the value is not immediately printed to the screen. Instead it is buffered within the process. This means it is not actually printed until after the fork operation hence you get it printed twice.
Adding the \n
though forces the buffer to be flushed and outputted to the screen. This happens before the fork and hence is only printed once.
You can force this to occur by using the fflush
method. For example
printf( "Hello, my pid is %d", getpid() );
fflush(stdout);
fork()
effectively creates a copy of the process. If, before calling fork()
, it had data that was buffered, both the parent and child will have the same buffered data. The next time that each of them does something to flush its buffer (such as printing a newline in the case of terminal output) you will see that buffered output in addition to any new output produced by that process. So if you are going to use stdio in both the parent and child then you should fflush
before forking, to ensure that there is no buffered data.
Often, the child is used only to call an exec*
function. Since that replaces the complete child process image (including any buffers) there is technically no need to fflush
if that is really all that you are going to do in the child. However, if there may be buffered data then you should be careful in how an exec failure is handled. In particular, avoid printing the error to stdout or stderr using any stdio function (write
is ok), and then call _exit
(or _Exit
) rather than calling exit
or just returning (which will flush any buffered output). Or avoid the issue altogether by flushing before forking.
참고URL : https://stackoverflow.com/questions/2530663/printf-anomaly-after-fork
'Programing' 카테고리의 다른 글
jQuery에서 oncut, oncopy 및 onpaste를 어떻게 처리합니까? (0) | 2020.11.18 |
---|---|
Mercurial 무시 파일 (0) | 2020.11.18 |
자바 스크립트로 팝업을 열고 사용자가 닫을 때 감지 할 수 있습니까? (0) | 2020.11.18 |
쉘 스크립트에서 'cd'를 실행하고 스크립트가 끝난 후에도 거기에 머무르는 방법? (0) | 2020.11.18 |
Maven없이 Eclipse Java 프로젝트에 대한 모든 JUnit 테스트를 동시에 실행하는 방법은 무엇입니까? (0) | 2020.11.18 |