printf output interleave

questions

Will following program's output interleave when OUT_STREAM is stdout? What about OUT_STREAM is stderr? why?

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

//#define OUT_STREAM stdout
#define OUT_STREAM stderr
#define COUNT 5

int main()
{
    int i = 0;
    printf("start\n");
    pid_t pid = fork();
    if (pid > 0) {
        while (i++ < COUNT) {
            fprintf(OUT_STREAM, "%d", 1);
            sleep(1);
        }
        printf("\n");
    }
    else if (pid == 0) {
        while (i++ < COUNT) {
            fprintf(OUT_STREAM, "%d", 0);
            sleep(1);
        }
        printf("\n");
    }
    else {
        printf("fork err\n");
    }
}

answer

/* #define OUT_STREAM stdout */
hfyin@hfyin-VirtualBox:~/projects/c$ gcc -o child -g child.c 
hfyin@hfyin-VirtualBox:~/projects/c$ ./child 
start
11111
00000

/* #define OUT_STREAM stderr */
hfyin@hfyin-VirtualBox:~/projects/c$ gcc -o child -g child.c 
hfyin@hfyin-VirtualBox:~/projects/c$ ./child 
start
1001101001

The  three  types  of  buffering  available are unbuffered, block buffered, and line buffered.  When an output stream is unbuffered, information appears on the destination file or terminal as soon as written; when it is block  buffered  many characters are saved up and written as a block; when it is line buffered characters are saved up until a newline is output or input is read from any stream attached to a terminal device (typically stdin).  The  function  fflush(3)  may  be used to force the block out early.  (See fclose(3).)

Normally all files are block buffered.  If a stream refers to a terminal (as stdout normally does), it is line buffered. The standard error stream stderr is always unbuffered by default.

-------------------------------------------------

More

Is the number of printed 0/1 always 10? Is there any chance less than 10 number printed? like the output is: 010101 (only 6 number). Why?

tips: fork() copies file descripter table from parent process to child process, but each underlying file offset is shared between parent and child. The offset is shared only when they are derived from the same original file descriptor by a sequences of fork() and dup() calls. Otherwise file descriptors do not share offsets, even if they resulted from open calls for the same file.

questions

what's the difference between following 2 commands in line 5 and line 6? Why?

$ ls child no
ls: cannot access 'no': No such file or directory
child

$ ls child no > t.c 2>t.c  
$ ls child no > t.c 2>&1 

output

$ ls child no > t.c 2>t.c ; cat t.c 
child
nnot access 'no': No such file or directory

$ ls child no > t.c 2>&1 ; cat t.c 
ls: cannot access 'no': No such file or directory
child

 

发布了6 篇原创文章 · 获赞 0 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览