On Windows, how does console window ownership work?

前端 未结 6 715
無奈伤痛
無奈伤痛 2021-01-13 01:05

When a console application is started from another console application, how does console ownership work?

I see four possibilities:

  1. The second applicati
6条回答
  •  别那么骄傲
    2021-01-13 01:44

    My guess is somewhere between 3 and 4. The console is a self-standing object, which has standard input, output and error streams. These streams are attached to the first process that uses the console. Subsequent processes can also inherit these streams if not redirected (e.g. running a command with redirect to a file.)

    Normally there is no contention, since parent processes usually wait for their child process to complete, and asynchronous processes typically start their own console (e.g. try "start cmd" in a command prompt) or redirect standard output.

    However, there is nothing to stop both processes writing to the output stream at the same time - the streams are shared. This can be a problem when using some runtime libraries since writes to standard output/error may not be immediately flushed, leading to mixed garbled output. In general, having to processes actively writing to the same output stream is usually not a good idea, unless you take measures to co-ordinate their output through concurrency primitives like Mutexes, Events and the like.

提交回复
热议问题