bash 防止 printf 中断另一个 printf

bash 防止 printf 中断另一个 printf

我有以下测试脚本。

#!/bin/bash

function foo {
  printf "Test line break: $1\nafter line break\n\n"
}

for VARIABLE in {1..30}
do
  foo $VARIABLE &
done
wait

现在我多次执行该脚本,有时输出如下所示:

Test line break: 15
Test line break: 14
after line break: 14
after line break: 15


Test line break: 16
after line break: 16

而不是预期的:

Test line break: 15
after line break: 15

Test line break: 14
after line break: 14

Test line break: 16
after line break: 16

如何防止 printf “中断”另一个 printf,但仍在后台运行它?

对我来说,问题似乎出在 printf 中的“\n”。

答案1

事实上你需要一个互斥体:

每个子 shell 都会同时访问相同/dev/stdout的父 shell,因此即使在同一函数内也无法确保顺序。为了确保这一点,您需要一个强制互斥的锁,即:/dev/stdout在释放锁之前,所有其他进程都不会开始写入。

#!/bin/bash

function foo {
lockdir=/tmp/myscript.lock
 mkdir "$lockdir" 2>/dev/null
while [ $? -ne 0 ]; do mkdir "$lockdir" 2>/dev/null; done
printf "Test line break: $1\nafter line break: $1\n\n"
rm -rf $lockdir
}

for VARIABLE in {1..30}
do
  foo $VARIABLE &
done
wait

这将给出以下结果:

$ bash plop1 2>/dev/null
Test line break: 5
after line break: 5

Test line break: 3
after line break: 3

Test line break: 11
after line break: 11

Test line break: 23
after line break: 23

Test line break: 14
after line break: 14

Test line break: 17
after line break: 17

Test line break: 24
after line break: 24

Test line break: 21
after line break: 21

Test line break: 27
after line break: 27

Test line break: 6
after line break: 6

Test line break: 2
after line break: 2

Test line break: 9
after line break: 9

Test line break: 26
after line break: 26

Test line break: 29
after line break: 29

Test line break: 20
after line break: 20

Test line break: 1
after line break: 1

Test line break: 12
after line break: 12

Test line break: 4
after line break: 4

Test line break: 13
after line break: 13

Test line break: 10
after line break: 10

Test line break: 15
after line break: 15

Test line break: 28
after line break: 28

Test line break: 25
after line break: 25

Test line break: 19
after line break: 19

Test line break: 18
after line break: 18

Test line break: 8
after line break: 8

Test line break: 7
after line break: 7

Test line break: 16
after line break: 16

Test line break: 22
after line break: 22

Test line break: 30
after line break: 30

相关内容