c - 在输出中看不到execl之前打印

标签 c linux exec printf waitpid

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>

int main(void)
{
    pid_t Checksum_pid = fork();

    if (Checksum_pid < 0)
        printf("Fork Failed\n");
    else if (Checksum_pid == 0)
    {
    printf("\nInside Child Process before execl");        
    //execl("/bin/sleep", "/bin/sleep", "2", NULL);
    execl("/bin/ls","ls",(char *)NULL) ;
        //exit(EXIT_FAILURE);
    printf("\nInside Child Process after execl\n");
    exit(EXIT_FAILURE);
    }
    else
    {
        int childStatus;        
    printf("\nInside Parent Process");
    sleep(5);
    pid_t returnValue = waitpid(Checksum_pid, &childStatus, WNOHANG);

        if (returnValue > 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


现在,如果我将删除parent中的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的第三个参数,然后在下面的输出中显示了任何child的打印内容:

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)的输出通常是行缓冲的。这意味着输出缓冲区将在换行符上刷新。由于您要打印的字符串后没有换行符,因此不会清除输出缓冲区。

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

关于c - 在输出中看不到execl之前打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57704311/

相关文章:

c - "while()"功能?

c - 函数通过c中的多个定界符将字符串拆分为数组

java - 如何在单台 linux 机器上创建 50000 个 tcp 连接?

c - 在 C 中将 const char 参数传递给 static char *argv[] 的语法

c - malloc on (char**)

c - 使用 execvp() 运行 'wc' 识别/home/usr/foo.txt 但不是 ~/foo.txt

c - 请解释一下C程序的这个功能是如何工作的?

c - 在c中使用ptrace从另一个进程读取一 block 内存

python - 无法解析参数

linux - 使用 GCC 命令提示符