加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么这个简单的代码使用`exit`而不能使用`_exit`?

发布时间:2020-12-16 10:12:34 所属栏目:百科 来源:网络整理
导读:请看一下这个示例代码,它使用一个非常完善的编程模式将stdout重定向到管道. #include stdio.h#include unistd.hint main(int argc,char **argv){ int fd[2]; pipe(fd); pid_t pid = fork(); if (pid == 0) { close(fd[0]); dup2(fd[1],1); printf("A string"
请看一下这个示例代码,它使用一个非常完善的编程模式将stdout重定向到管道.

#include <stdio.h>
#include <unistd.h>

int main(int argc,char **argv)
{
    int fd[2];
    pipe(fd);

    pid_t pid = fork();
    if (pid == 0) {
        close(fd[0]);
        dup2(fd[1],1);
        printf("A string");
        _exit(0);
    }

    close(fd[1]);
    char text[1000];
    size_t size;
    int p = 0;
    while ((size = read(fd[0],text+p,1)) == 1) {
        p++;
    }
    close(fd[0]);
    text[p] = '';
    printf("%s",text);

    return 0;
}

代码实际上不起作用.正如@kaylum在评论中正确建议的那样,在子进程中调用exit而不是_exit会使代码正常工作.

解决方法

exit()将所有打开的流作为其终止的一部分刷新,而_exit()不刷新 – 因此在调用_exit()时,任何缓冲的输出都会丢失.

你可以让它“工作”:

1)通过调用fflush(stdout);在调用_exit()或之前刷新缓冲的输出
2)使用setbuf(stdout,0)禁用stdout的缓冲;在main()的开头.

POSIX要求流被exit()刷新:

The exit() function shall then flush all open streams with unwritten
buffered data and close all open streams. Finally,the process shall
be terminated [CX] with the same consequences as described in
Consequences of Process Termination.

同样,要求在_exit()之前不刷新流:

The _Exit() [CX] and _exit() functions shall not call functions registered with atexit() nor any registered signal handlers. [CX] Open streams shall not be flushed. Whether open streams are closed (without flushing) is implementation-defined. Finally,the calling process shall be terminated with the consequences described below.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读