私はそれを説明できない問題があります。なぜ私はvalgrindとfork()を使って異なる出力を持っていますか
メモリリークについて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)
私はフォークで新しく、これが問題であるかどうかわかりません私には、そうではありません。なぜこれが起こるのですか?
これは、漏れをチェックするために、GCC 7
なぜ、最初に親の出力と子供の出力の間に特定の順序が期待されますか? –
@AndrewHenleあなたは、これらのプロセスの制御フローが異なる可能性があり、私はそれを中継できないことを意味しますか?私は、親プロセスと子プロセスに別々のアドレス空間があることを知っていますが、その順序についてはわかりませんでした。 – Michi
2つの異なるプロセスには2つの異なるスレッドがあり、並列に実行されます。どのように2つの間ですべての動きがやや複雑ですが、いいえ、特定の順序でタスクを実行することに依存することはできません。これは競合状態のように聞こえる。 – Thebluefish