简体   繁体   中英

launch process in background and modify it from bash script

I'm creating a bash script that will run a process in the background, which creates a socket file. The socket file then needs to be chmod 'd. The problem I'm having is that the socket file isn't being created before trying to chmod the file.

Example source:

#!/bin/bash

# first create folder that will hold socket file
mkdir /tmp/myproc
# now run process in background that generates the socket file
node ../main.js &
# finally chmod the thing
chmod /tmp/myproc/*.sock

How do I delay the execution of the chmod until after the socket file has been created?

The easiest way I know to do this is to busywait for the file to appear. Conveniently, ls returns non-zero when the file it is asked to list doesn't exist; so just loop on ls until it returns 0, and when it does you know you have at least one *.sock file to chmod.

#!/bin/sh
echo -n "Waiting for socket to open.."
( while [ ! $(ls /tmp/myproc/*.sock) ]; do
  echo -n "."
  sleep 2
done ) 2> /dev/null
echo ". Found"

If this is something you need to do more than once wrap it in a function, but otherwise as is should do what you need.

EDIT:

As pointed out in the comments, using ls like this is inferior to -e in the test, so the rewritten script below is to be preferred. (I have also corrected the shell invocation, as -n is not supported on all platforms in sh emulation mode.)

#!/bin/bash
echo -n "Waiting for socket to open.."
while [ ! -e /tmp/myproc/*.sock ]; do
  echo -n "."
  sleep 2
done
echo ". Found"

Test to see if the file exists before proceeding:

while [[ ! -e filename ]]
do
    sleep 1
done

If you set your umask (try umask 0 ) you may not have to chmod at all. If you still don't get the right permissions check if node has options to change that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM