微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

读取和写入关闭的文件描述符

如何解决读取和写入关闭的文件描述符

考虑这个代码

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

int main(){
    int pfd[2];
    char buffer[512] = "111803142-Atharva\n",buffer2[512];
    pid_t pid;
    pipe(pfd);
    pid = fork();
    if(pid == 0){
        close(pfd[0]);
        dup2(pfd[1],1);
        close(pfd[1]);
        /* Closing STDOUT won't print to screen
         * Applying the same logic,after closing pfd[1]
         * data shouldn't go to the pipe ?
        */ 
        printf("%s",buffer);
        exit(0);
    }
    else{
        wait(0);
        close(pfd[1]);
        dup2(pfd[0],0);
        close(pfd[0]);
        /* 
         * Similarly,after closing pfd[0]
         * scanf should no longer be able to read from it
        */ 
        scanf("%s",buffer2);
    }
    printf("Data : %s\n",buffer2);
    return 0;
}

代码运行良好,其 o/p 如下:

Data : 111803142-Atharva

我在评论添加了我的疑问。我想知道为什么 printf() 和 scanf() 在关闭给定的文件描述符后仍然能够写入/读取它们?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。