Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Multithreading 在unix中,两个不同的后台进程访问同一个文件会发生什么情况?_Multithreading_Shell_Unix_Process - Fatal编程技术网

Multithreading 在unix中,两个不同的后台进程访问同一个文件会发生什么情况?

Multithreading 在unix中,两个不同的后台进程访问同一个文件会发生什么情况?,multithreading,shell,unix,process,Multithreading,Shell,Unix,Process,请在下面的cmd上向我解释: touch temp.txt touch temp1.txt who > temp.txt & cat temp.txt | wc -l >temp1.txt & 假设temp.txt文件为空文件。 那么,在执行之后,temp.txt和temp1.txt文件中会出现什么呢 有人能解释一下可能的情况吗,因为作业是在后台模式下运行的?当cat运行时temp.txt的状态超出了您的控制范围(当cat和谁相对运行时取决于调度程序),因此您无法

请在下面的cmd上向我解释:

touch temp.txt
touch temp1.txt
who > temp.txt &
cat temp.txt | wc -l >temp1.txt  &
假设temp.txt文件为空文件。 那么,在执行之后,
temp.txt
temp1.txt
文件中会出现什么呢


有人能解释一下可能的情况吗,因为作业是在后台模式下运行的?

cat
运行时
temp.txt
的状态超出了您的控制范围(当
cat
谁相对运行时取决于调度程序),因此您无法预测会发生什么。更安全的版本是

# These two commands are unnecessary. The files will be created
# when opened for writing.
# touch temp.txt
# touch temp1.txt
who | tee temp.txt | wc -l > temp1.txt &  # If it really needs to run in the background
视情况而定
cat(1)
可能会在其输入文件中看到一些东西或什么也看不到

下面是最后两个命令的大致情况。(我忽略了
touch(1)
调用,因为它们是同步的。)

  • who>f1

    子对象被分叉,输出文件被关闭,输出文件被移动到子对象的标准输出,并运行一个新程序
  • cat f2|wc-l>f2

    一个子对象是分叉的,一个管道是分叉的,另一个子对象是分叉的,子对象将其管道末端移动到标准输入或标准输出(视情况而定),一个子对象运行一个命令以打开输入文件,另一个子对象执行输出,依此类推
我不能保证这就是你的壳在做的事情——也许它在分叉前会撞击,等等——但这已经足够接近了。因此,让我们将这些shell命令放在时间维度上:

[time =====================================================================>]

# who >f1
-?->[clobber *f1*]-?->[dup to stdout]-?->[exec who(1)]-?->[...]

# cat f1 | wc -l>f2
-?->[pipe]-?->[fork]-?->[dup pipe]-?->[clobber *f2*]-?->[dup to stdout]-?->[exec wc(1)]
                +----?->[dup pipe]-?->[exec cat(1)]-?->[open *f1*]-?->[...]

上面的每一个
-?->
箭头都可以任意长或短,这是您无法控制的。可能在第一次碰撞之前(看到旧数据?)运行了
cat(1)
,可能没有。可能是在
谁(1)
有机会写入输出之前运行的,可能不是。

这取决于具体情况。一般来说:不好的事情。未定义的行为会发生。如果两个前台进程访问同一个文件,没有什么特别的不同。计时和缓冲都会在不确定的结果中起作用,所以写和访问之间基本上是有区别的。在这里,您只需写入temp.txt,然后读取temp.txt,这样就不会发生任何不好的事情。您将在一个文件中输入行数,并在第二个文件中输出行数。就是这样。这里的后台工作速度很快,它们会做一些事情并完成,所以这里没有真正的并行性。如果它们总是在运行,那么我们可以考虑不同的场景。