설명 할 수없는 문제점이 있습니다.fork()를 사용하여 valgrind와 다른 출력을 갖는 이유
메모리 누수에 대해 valgrind
으로 확인 프로그램이 인쇄되는 순서가 프로그램 실행 파일을 실행 한 순서와 다른 것으로 나타났습니다.
내 프로그램을 축소하여 문제가 어디에 있는지 보여주기 위해 컴파일했습니다.
내가 컴파일하고 다음 코드를 실행합니다
[email protected] ~ $ ./program
I am 18320
Fork returned 18321
I am the parent waiting for child to end
Fork returned 0
I am the child with pid 18321
Child exiting...
Parent ending.
하지만 valgrind
그것을 확인할 때, 나는 다른 순서로 출력을 얻을 : 나는 다음과 같은 출력을 얻을
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(void)
{
printf("I am %d\n", (int)getpid());
pid_t pid = fork();
printf("Fork returned %d\n", (int)pid);
if (pid < 0){
perror("Fork Faild\n");
exit(1);
}
if (pid == 0){
printf("I am the child with pid %d\n", (int)getpid());
sleep(5);
printf("Child exiting...\n");
exit(0);
}
printf("I am the parent waiting for child to end\n");
wait(NULL);
printf("Parent ending.\n");
return 0;
}
을
[email protected] ~ $ valgrind --leak-check=full --track-origins=yes ./program
==18361== Memcheck, a memory error detector
==18361== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==18361== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==18361== Command: ./program
==18361==
I am 18361
Fork returned 18362
Fork returned 0
I am the child with pid 18362
I am the parent waiting for child to end
Child exiting...
==18362==
==18362== HEAP SUMMARY:
==18362== in use at exit: 0 bytes in 0 blocks
==18362== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==18362==
==18362== All heap blocks were freed -- no leaks are possible
==18362==
==18362== For counts of detected and suppressed errors, rerun with: -v
==18362== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
Parent ending.
==18361==
==18361== HEAP SUMMARY:
==18361== in use at exit: 0 bytes in 0 blocks
==18361== total heap usage: 1 allocs, 1 frees, 1,024 bytes allocated
==18361==
==18361== All heap blocks were freed -- no leaks are possible
==18361==
==18361== For counts of detected and suppressed errors, rerun with: -v
==18361== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
저는 포크가 처음이에요. 이것이 문제가되는지 이해할 수 없습니다. 나에게. 왜 이런 일이 일어나는가?
이
은 누수를 확인하기 위해 7
왜 처음에는 부모 출력물과 자식 출력물간에 특정 순서가 올 것으로 예상됩니까? –
@AndrewHenle 당신은 이러한 프로세스의 제어 흐름이 다를 수 있다는 것을 의미합니다. 나는 부모와 자식 프로세스가 별도의 주소 공간을 가지고 있음을 알고 있지만 순서에 대해서는 확신하지 못했습니다. – Michi
두 개의 다른 프로세스는 두 개의 서로 다른 스레드를 가지므로 병렬로 실행됩니다. 둘 사이에서 모든 일이 다소 복잡해 지지만, 특정 순서로 작업을 실행하는 것에 의존 할 수는 없습니다. 경쟁 조건처럼 들립니다. – Thebluefish