c - 为什么我使用 fork() 的 valgrind 得到不同的输出

标签 c fork valgrind linux-mint gcc7

我有一个无法解释的问题。

使用 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;
}

我得到以下输出:

michi@michael ~ $ ./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 检查它时,我以另一种顺序得到输出:

michi@michael ~ $ 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)

我是 fork 新手,我不明白这对我来说是否是一个问题。为什么会出现这种情况?

这是在 Linux Mint 18.2 和 GCC 7 上编译的。

最佳答案

Valgrind “检测”您的代码以检查是否存在泄漏。这意味着添加额外的代码、变量等。This答案对此提供了非常快速的概述。

在一组情况下,您的程序可能“通常”按特定顺序执行。但是,如果您更改这些情况(例如,使用 valgrind 进行检测),运行顺序可能会发生变化。这将取决于许多因素,包括调度程序等。

这是一个非常简单的答案,但本质上,除非您使用自己的调度程序、信号量等控制代码流,否则如果您大幅更改代码/环境,感知的执行顺序可能会改变。

关于c - 为什么我使用 fork() 的 valgrind 得到不同的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47521084/

相关文章:

c - c中的openssl aes_128_ctr

C- Unix 套接字 - 非阻塞读取

c - 两个进程读取相同的标准输入

bash - 如何杀死shell的所有子进程?

c - Valgrind 下的程序输出显着不同

c - 需要左值作为增量操作数错误指针

c - 为什么当我打印时,十进制的 *str 显示为 80(ASCII 字母 P)?

c - 我错误地使用了 close() 吗?

c++ - valgrind 无法识别无效写入

c - Valgrind 中抑制泄漏意味着什么?