分叉进程和共享变量

分叉进程和共享变量

我有一个 bash 脚本,其中有两个分叉函数,它们都写入日志。当两个函数都完成后,我想删除这个日志。

但我遇到的问题是,processFinishCount永远不会大于 1。每个分叉进程是否都会获取一个复制共享变量并在调用时增加该副本delete_log

我如何确保变量正确增加?

processFinishCount=0

delete_log()
{
    let processFinishCount++
    if ["$processFinishCount" == 2]; then
        rm log.txt

    else
        echo `$processFinishCount task(s) finished" >> log.txt
    fi
}

function_one()
{
    ...
    delete_log
}
function_two()
{
    ...
    delete_log
}

function_one &
function_two &

答案1

一个进程中的全局变量不会在另一个进程中更新。因此可以使用外部文件。我会得到类似这样的结果(未检查准确性)。

delete_log()
{
    touch /tmp/$1
    if [ -e $status_file1 -a -e $status_file2 ]
    then 
        rm log.txt
    else
        echo log >> log.txt
    fi
}

f1()
{
    ...
    delete_log $1
}

f2()
{
    ...
    delete_log $1
}

f1 fork1.done &
f2 fork2.done &

答案2

您可以使用wait等待所有子进程完成。这将a在 3 秒后打印:

sleep 3 &
sleep 1 &
wait
echo a

help wait

wait: wait [id]
    Wait for job completion and return exit status.

    Waits for the process identified by ID, which may be a process ID or a
    job specification, and reports its termination status.  If ID is not
    given, waits for all currently active child processes, and the return
    status is zero.  If ID is a a job specification, waits for all processes
    in the job's pipeline.

    Exit Status:
    Returns the status of ID; fails if ID is invalid or an invalid option is
    given.

相关内容