zoukankan      html  css  js  c++  java
  • linux: c语言 关闭标准输出STDOUT_FILENO对父子进程的影响

    简介
    标准 I/O 库(stdio)及其头文件 stdio.h 为底层 I/O 系统调用提供了一个通用的接口。这个库现在已经成为 ANSI 标准 C 的一部分。

    标准 I/O 库提供了许多复杂的函数用于格式化输出和扫描输入。在很多方面,你使用的标准 I/O 库的方式和使用底层文件描述符一样,
    需要先打开一个文件以建立一个访问路径,这个操作的返回值将作为其他 I/O 库函数的参数。
    在标准 I/O 库中,与底层文件描述符对应的是流(stream,需要注意的是这个流与 C++ 中的输入输出流不一样),
    它被实现为指向结构 FILE 的指针(文件指针)。

    在启动程序时,有 3 个文件流是自动打开的,它们是 stdin、stdout 和 stderr,

    在 stdio.h 中定义,分别代表着标准输入、标准输出和标准错误输出,与底层文件描述符 0、1、2 相对应。

    可用的文件流数量与文件描述符一样,都是有限制的,实际的限制由头文件 stdio.h 中定义的 FOPEN_MAX 来定义,它的值至少为 8,在 Linux 系统中,通常是 16。



    #在子进程中关闭标准输出,观察对父进程的影响




    #include<stdio.h> #include<unistd.h> #include<sys/wait.h> #include<sys/types.h> int main(){ int rc=fork(); if(rc==0){ printf("child print a word "); fclose(stdout); printf("not print "); }else{ wait(NULL); printf("father"); } return 0;} [root@localhost codec5]# ./t7 child print a word father

    显然在再子进程中关闭对父进程并没有影响。

    下面我们用waitpid使子进程等待父进程,然后再父进程里面调用了fclose(stdout)将标准输出关掉了,父进程后面的没有输出,子进程正常

    #include<stdio.h>
    #include<unistd.h>
    #include<sys/wait.h>
    #include<sys/types.h>
    int main(){
    int w=(int)getpid();
    int rc=fork();
    if(rc==0){
    waitpid(w,NULL,0);
    printf("child  print a word
    ");
    printf("not print 
    ");
    
    }else{
    printf("output
    ");
    fclose(stdout);
    printf("father
    ");
    
    }
    
    
    return 0;}
    
    
    
    [root@localhost codec5]# ./t7
    output
    [root@localhost codec5]# child  print a word
    not print 

    如果在fork前调用fclose(stdout)很显然父子进程均不会有任何输出

    如下代码

    #include<stdio.h>
    #include<unistd.h>
    #include<sys/wait.h>
    #include<sys/types.h>
    int main(){
    fclose(stdout);
    
    int rc=fork();
    if(rc==0){
    
    printf("child  print a word
    ");
    printf("not print 
    ");
    
    }else{
    printf("output
    ");
    
    printf("father
    ");
    
    }
    
    
    return 0;}
    
    
    无输出
  • 相关阅读:
    C语言-if语句
    C语言-表达式
    C语言-基础
    Java for LeetCode 187 Repeated DNA Sequences
    Java for LeetCode 179 Largest Number
    Java for LeetCode 174 Dungeon Game
    Java for LeetCode 173 Binary Search Tree Iterator
    Java for LeetCode 172 Factorial Trailing Zeroes
    Java for LeetCode 171 Excel Sheet Column Number
    Java for LeetCode 169 Majority Element
  • 原文地址:https://www.cnblogs.com/lhyzdd/p/13841664.html
Copyright © 2011-2022 走看看