linuxshell

run an input/output waiting application in function in background getting output of that function


I have a shell function

func() {
    read < /dev/ttyUSB3 &
    PID=$!
    echo "$PID"
}

do not focus on its exact purpose, the thing is that I need to run some app (in this case read) in background, and get its pid to kill in the future.

The problem I get is, in calling script

MYVAR=$(func)

is hung. I suspect it waits for termination of the background process (e.g. its stdout close), but why?

Simpler deal:

echo $(read < /dev/ttyUSB3 &)

also hangs, ^C does not work anymore, ^Z too.

I would expect echo to return empty string, as read starts, goes into background and says nothing into the stdout. When echo ends, that read process will become zombie.

Something is obviously broken in my logic. What is it?

How do I run input/output waiting application into background letting it do what it needs to, getting its PID without further problems like this? I have tried doing return from the function, but for some reason it truncates PID value being returned into 8-bit value.

Edit:

Thanks Barmar for the suggestion. I have chosen bad example. In my case I already perform output to the waiting device file using echo:\

func() {
    echo "something" > /dev/ttyUSB3 &
    PID=$!
    echo "$PID"
}

and is call

MYVAR=$(func)

hangs at the exit of the function.


Solution

  • I have solved the issue after getting another problem.

    The problem was in inability to kill the process employing the echo to the device file. The script being killed has trap set, and its trap code was never invoked (possible Linux bug?). But it was clear that when script process was tried to be killed, the write to device file restarts.

    The cause was the driver returning -ERESTARTSYS instead of -EINTR, causing the current driver write process terminate, but being restarted without going into user space. This means if system call is restartable through -ERESTARTSYS, you'll not be able to terminate related I/O until it finishes naturally.