execl之前的打印在输出中不可见

#include  #include  #include  #include  #include  int main(void) { pid_t Checksum_pid = fork(); if (Checksum_pid  0) { if (WIFEXITED(childStatus)) printf("\nChild Exit Code: %d\n", WEXITSTATUS(childStatus)); else printf("\nChild Exit Status: 0x%.4X\n", childStatus); } else if (returnValue == 0) printf("\nChild process still running\n"); else { if (errno == ECHILD) printf("\nError ECHILD!!\n"); else if (errno == EINTR) printf("\nError EINTR!!\n"); else printf("\nError EINVAL!!\n"); } printf("\nParent: I am about to finish\n"); } return 0; } 

输出:

 kth4kor-2:~/bosch/Test1$ ./a.out a.out ___waitpid_test1 waitpid_test1~ waitpid_test1.c waitpid_test1.c~ waitpid_test2.c waitpid_test2.c~ Inside Parent Process Child Exit Code: 0 Parent: I am about to finish 

现在,如果我将删除父节点中的sleep(5),则输出:

 kth4kor-2:~/bosch/Test1$ ./a.out Inside Parent Process Child process still running Parent: I am about to finish kth4kor@g3gdev-kth4kor-2:~/bosch/Test1$ a.out ___waitpid_test1 waitpid_test1~ waitpid_test1.c waitpid_test1.c~ waitpid_test2.c waitpid_test2.c~ 

最后我尝试使用0作为waitpid而不是WNOHANG的第三个参数然后它给了我以下输出与任何打印的孩子:

 kth4kor-2:~/bosch/Test1$ ./a.out a.out ___waitpid_test1 waitpid_test1~ waitpid_test1.c waitpid_test1.c~ waitpid_test2.c waitpid_test2.c~ Inside Parent Process Child Exit Code: 0 Parent: I am about to finish 

在执行execl之后和执行之前,有人可以帮助我理解进程的行为吗?

请记住,通过printf (到stdout )的stdout通常是行缓冲的 。 这意味着输出缓冲区在换行符上刷新。 由于在要打印的字符串后没有换行符,因此不会刷新输出缓冲区。

在字符串中最后添加换行符,或者使用fflush手动刷新缓冲区。