English 中文(简体)
为什么我放弃方案的产出在我掌握产出时有所不同?
原标题:Why is the output of my forking program different when I pipe its output?

我正在研究一些简便法典,并决定为我尝试。 我汇编后从Emacs内部管理,从Bash的操作中得出不同产出。

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

int main() {
  if (fork() != 0) {
    printf("%d: X
", getpid());
  }

  if (fork() != 0) {
    printf("%d: Y
", getpid());
  }

  printf("%d: Z
", getpid());
}

我用gcc进行汇编,然后从Emacs内部抽取,然后排入catgrep .

2055: X
2055: Y
2055: Z
2055: X
2058: Z
2057: Y
2057: Z
2059: Z

这项权利。 只是从Bash I获得(我预计)

2084: X
2084: Y
2084: Z
2085: Y
2085: Z
2087: Z
2086: Z

edit - 忽略了一些新条线<>。

什么进展?

最佳回答

不同过程撰写产出的顺序完全无法预测。 因此,唯一令人惊讶的是,有时“X”打印说明有两次发生。

我认为,这是因为有时在第二个<代码>fork()上,包括“X”的产出线处于产出缓冲,需要加以冲淡。 因此,这两个过程最终都印刷了它。 由于getpid()已被称作并转化成星体,因此其脂肪显示相同。

我能够复制多条“X”线,但如果在第二个<条码>之前添加<条码>fflush(stdout);,则我总是看一看“X”线,总共有7条线。

问题回答

我认为,我知道正在发生什么。 当产出是相对的,而当它有管道或档案时,则 st的缓冲将有所不同。 儿童继承父母的缓冲。 当他们重新流动时,你可以取得双重产出。

如果是,

fflush(stdout);

页: 1

有趣的是,当标准产出是一种相对工具时,它会有所不同。 或许,图书馆知道这意味着什么,每条线中断后流利,或像这样的情况。

因此,我想到的是,你们为什么要获得一个以上的“X”?

这是因为缓冲产出正在两次流动。

当你掌管一个方案产出时, st图书馆认识到,你的产出不是终点站,而是阻止缓冲而不是线性缓冲。 因此,当 process子和现在的母子和孩子都等待产出时,就没有任何产出。

如果您在登机之前一直使用<代码>stdout,请在fflush(stdout)之前(fork(<>>)(并同样使用任何其他产出FILE)。 如果不这样做,就会导致未界定的行为。 您所看到的效应来自stdout _line-buffered。 当它与一个终点站连接时,在连接管道时缓冲<>。 这不是要求,而是标准建议。





相关问题
Fastest method for running a binary search on a file in C?

For example, let s say I want to find a particular word or number in a file. The contents are in sorted order (obviously). Since I want to run a binary search on the file, it seems like a real waste ...

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

Tips for debugging a made-for-linux application on windows?

I m trying to find the source of a bug I have found in an open-source application. I have managed to get a build up and running on my Windows machine, but I m having trouble finding the spot in the ...

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

Good, free, easy-to-use C graphics libraries? [closed]

I was wondering if there were any good free graphics libraries for C that are easy to use? It s for plotting 2d and 3d graphs and then saving to a file. It s on a Linux system and there s no gnuplot ...

Encoding, decoding an integer to a char array

Please note that this is not homework and i did search before starting this new thread. I got Store an int in a char array? I was looking for an answer but didn t get any satisfactory answer in the ...