0
bash: $: yes a
[some output] then press Ctrl+Z
      $: yes b
[some output] then press Ctrl+Z

then, do bg twice and got some output:

a b b b a a a a b a a a a b b a b a a a a a b a a a b a a b a a ... a b b b b b b b b etc.

Why a and b interchange so casually?

3 Answers3

3

This has to do process scheduling, which is a fairly complex topic.

I don't know enough on the topic to explain precisely why it is random, but it suffices to say that the Linux kernel is deciding how much CPU time each process gets, and based on how many other processes are also running and what exactly they are doing, it can change dramatically.

adamdunson
  • 2,635
  • 1
  • 23
  • 27
  • I noticed that the interchange changes when I try to type any character in the console or move my mouse: D – HazardousWish Mar 08 '13 at 17:26
  • IIRC things like keyboard and mouse I/O are highest priority, whereas userland processes typically have relatively low priority. E.g., running `yes &>/dev/null &` and viewing it in `top` shows it at priority 20 (the lowest). – adamdunson Mar 08 '13 at 17:34
0

Because both processes are running simultaneously? Isn't that what you would have expected?

Svend Hansen
  • 3,277
  • 3
  • 31
  • 50
  • May be, but why not 'ababababababababa'? – HazardousWish Mar 08 '13 at 17:18
  • I guess it depends on when each process gets CPU time, and for how long it holds on to it (combined with other things like output buffers, etc)... – Svend Hansen Mar 08 '13 at 17:20
  • race condition and inaccuracy timer? – HazardousWish Mar 08 '13 at 17:20
  • There's no reason (as far as I know) that each process would output just once and give up the cpu. And then, I guess (this is speculation) the threads _could_ be outputting ababababab, but because the output buffers aren't flushed immediately (are they?) the order might appear differently... maybe... – Svend Hansen Mar 08 '13 at 17:23
0

Incidentally, yes doesn't usually give a string all on one line, so I'm assuming that you mean that you want: a
b
a
b
a
b

I can't think of any shorter way to do that with standard unix commands than this:

awk 'BEGIN{while (1){print "a\nb"}}'

BenPen
  • 383
  • 4
  • 14