Skip to content

"... &" background statement cannot work with functions? #238

Open

Description

@sdothum

Does the "... &" statement only work with simple commands and not functions? For example, if I have defined

function q; echo $argv; sleep 10s; echo $argv; end

and execute

q 1 &; q 2 &; q 3 &

the output is

1
1
2
2
3
3
Job 3, “q 3 &” has ended
Job 2, “q 2 &” has ended
Job 1, “q 1 &” has ended

with the observed performance (delay) indicating that each successive "q" command is not executed until the previous command is completed. I use in POSIX sh "(sleep [some delay] && [command]) &" quite commonly in startup scripts e.g. for window managers to allow for the initialization requirements of certain apps.

If there is a correct "fish" way of spawning multiple background processes, my second question is: is there a way to spawn a block of commands in background similar to POSIX "(command1 && command2 && command3...) &". I tried "begin; ...statements...; end &" but fish does not like that!

Activity

  1. siteshwar commented on Jul 21, 2012

    @siteshwar
    Contributor

    On Linux, executing "vi &" doesn't take vi to background, and at exit I get following message :

    Job 1, “vi &” has ended

    Is anyone else able to reproduce it ?

  2. ridiculousfish commented on Jul 21, 2012

    @ridiculousfish
    Member

    fish probably doesn't spawn a subshell for functions executed as background jobs. If it did, those jobs probably could not do things like update global variables.

  3. smlx commented on Aug 12, 2012

    @smlx
    Contributor
    $ vi &
    Job 1, “vi &” has stopped
    

    Seems to work correctly here using fish packaged in debian:
    Version: 1.23.1+20120106.git8b407a3-1

    Could be a regression?

  4. siteshwar commented on Aug 12, 2012

    @siteshwar
    Contributor

    I had written a function named "vi" (alias like) to invoke vi editor, so I was not able to invoke vi in background. This should be fixed, we need to add support for executing functions in background.

  5. robacarp commented on Apr 26, 2013

    @robacarp

    This bit me in a rather confusing way just now.

    Several weeks ago I defined an alias: alias redis="redis-server /usr/local/etc/redis.conf" today, I was trying to run redis and elasticsearch together in the same console, both as background jobs, so that their output would be in the same shell and typed redis & elasticsearch &. Instead of what I was expecting, I got just the redis server and on exit, it spawned elasticsearch in a background job.

    I understand what you're saying about subshells for functions being overkill, but I think that, as with the !! syntax, if there is a way to achieve this functionality without changing things, it'll meet the expectations of more people migrating from bash/zsh, because you can background just about everything in a bash.

    Thanks again for all your work on this awesome shell!

  6. JanKanis commented on Apr 30, 2013

    @JanKanis
    Contributor

    This is a known problem, see also issue #563.

    Unlike most other shells fish is a multithreaded program, so it can not
    just be forked into a new subshell without coordinating the multiple
    threads. That could be done but no-one has taken the time to do so. The
    other (preferable) solution is to have background functions execute in
    different threads, this should be possible but would also require some work
    to be implemented.

  7. geoff-nixon commented on Oct 16, 2013

    @geoff-nixon
    Contributor

    Ah. Well that would also explain #1040 then, I think.

  8. maxnordlund commented on Oct 23, 2015

    @maxnordlund
    Contributor

    Hm, what if calls to builtins, like set, were synchronized? @ridiculousfish Then subshells could update global/universal variables but allow everything else to run concurrently, or am I missing something else?

  9. ridiculousfish commented on Oct 23, 2015

    @ridiculousfish
    Member

    @maxnordlund The biggest obstacle is that fish uses the C stack for builtins, functions, and command substitutions. Therefore executing two of these concurrently means multiple threads, multiple processes, or something like coroutines.

    I have a branch that tries to support multithreaded execution, but it's very complex so I'm not optimistic that it will work.

  10. maxnordlund commented on Oct 23, 2015

    @maxnordlund
    Contributor

    I was leaning towards multiple threads, and come to think of maybe it would be easier if script execution was always running in the background. Every time it needed a builtin it synchronized/sent a message to the main thread to do the work.

    Sort of like most GUI frameworks keep one thread responsible for rendering, and you always have to ask it if you need an update.

  11. Lucretiel commented on Oct 29, 2015

    @Lucretiel
    Contributor

    Fish shell already uses libevent, right? Couldn't we keep it single threaded, but switch builtin and function execution to an asynchronous or coroutine model? That solves the global state atomicity issue- only one piece of code is ever running at a time, so changes to variables, working directory, etc all happen atomically. Once all pipelines are converted to true unix pipes, rather than being fully buffered between functions (see #936), the pipe's file descriptors can be selected over in the libevent event loop, allowing for single-threaded concurrency in the same vein as node.js or python's asyncio.

    We should probably assume that users who are backgrounding fish functions are aware and accepting of the possibility of global state mutation, rather than attempting to simulate multiple working directories (for instance, with openat). This is already the behavior of background jobs that write to stdout. One of the main fish features is that it never forks except when launching a program, so cd and set and related commands never don't work as expected. Therefore, when a user writes:

    function contrived
        sleep 5
        set -g MY_VAR hello
        cd $argv[1]
    end
    
    contrived /another/directory

    The user clearly wants the current shell to switch to /another/directory and set MY_VAR globally to hello after 5 seconds. We should keep this behavior for background jobs- if the user instead does contrived /another/directory &, the working directory and variable should still be changed after 5 seconds, even though it happened in the background. This is the same as background jobs sharing stdout/stderr with the foreground. Fish doesn't currently have a mechanism for a "local" working directory, in the same way it has "local" variables; that should probably be a separate (though related) discussion. cd -l, anyone?

  12. ridiculousfish commented on Oct 29, 2015

    @ridiculousfish
    Member

    No, fish does not use libevent.

    Making the internals thread safe is part of it. There's also the issue of replicating process state. For example, we need to have multiple variable stacks, since two separately executing functions need independent local variables. We need separate values of $status. We need to have separate notions of "last backgrounded process" since functions may use that. We need separate working directories - I don't think it's acceptable to prohibit cd for two simultaneously executing functions.

    I did some work on this in the multithreaded_execution branch, but I think as it stands it adds too much complexity to merge, and if we want to go down this path, it will involve a lot of rewriting.

  13. added
    bug
    on Aug 29, 2016
  14. 7 remaining items

  15. sabinem commented on Jun 20, 2018

    @sabinem
    Contributor

    I think it is acceptable that functions cannot be put in the background, but it should be better communicated to the user. Now it just runs in the foreground anyway, even though the user requested the background: it is blocking the shell and in the end the user sees: Job 1, 'hello &' has ended even though there never was a job running in the background.

    I think in case of a request hallo &, where hello is a function, there should be a syntax error or other message, that tells the user that this command is a function and won't run in the background.

    What do you think about this? Fish stands for a friendly shell: it should tell the user what it does in my humble opinion.

  16. tbodt commented on Jul 10, 2019

    @tbodt

    You can work around the "has ended" message by putting the job start in a block: begin; sleep 5 &; end

  17. nemya9066 commented on Apr 3, 2021

    @nemya9066

    @sabinem I think it's also very important to birng the user attention to abbreviation. This is a feature not available in other shells most new users(and this is what happened to me) just copy their alias.sh to alias.fish source it and assume everything is gonna be okay then they run at issues such as #238 and assume their workflow is gonna be totally disrupted in fish.
    I think an even better way to deal with the alias situation is to add --silent functionality to abbreviation and replace aliases with those instead of functions this should be easier to implement than running functions in the background and better mimic the alias functionnality in other shells.

  18. nemya9066 commented on Apr 3, 2021

    @nemya9066

    A message such as this would be nice when running an alias command with &.
    shot
    I think it's important to bring the user attention to abbreviation when using an alias but maybe not so if the user use a regular function so there should be a way for fish to distinguish between alias functions and normal ones maybe by adding a specific description for functions created by alias?
    For normal functions we can just tell the user that functions can't be put in the background.

  19. stellarpower commented on Jan 18, 2022

    @stellarpower

    If it saves anyone 10 minuntes working out the correct way to quote, I believe this works (or will happily be corrected) as a workaround:

    function bgFunc  
        fish -c (string join ' ' (string escape $argv)) & 
    end
  20. weisi commented on Jan 18, 2022

    @weisi
    Contributor

    A slight improvement on @stellarpower's wonderful bgFunc wrapper above:

    function bgFunc
      fish -c (string join -- ' ' (string escape -- $argv)) &
    end

    (I happen to have arguments starting with -- which would get passed to string escape and string join as their arguments instead of string input if not using -- to explicitly mark the end of the arguments)

  21. LevitatingBusinessMan commented on Jan 15, 2024

    @LevitatingBusinessMan

    A message such as this would be nice when running an alias command with &. shot I think it's important to bring the user attention to abbreviation when using an alias but maybe not so if the user use a regular function so there should be a way for fish to distinguish between alias functions and normal ones maybe by adding a specific description for functions created by alias? For normal functions we can just tell the user that functions can't be put in the background.

    This wrongly assumes all functions are aliases.

  22. tmccombs commented on Dec 29, 2024

    @tmccombs
    Contributor

    Would this be any easier to implement after the rust rewrite?

  23. zanchey commented on Dec 29, 2024

    @zanchey
    Member

    Would this be any easier to implement after the rust rewrite?

    Yes, and it's one of the driving factors behind the port. (Please do not ask when it is planned or when it will be ready; we can give no answers that you can action.)

  24. tobia commented on Feb 6, 2026

    @tobia

    The other (preferable) solution is to have background functions execute in different threads

    Agree 100%. If I can add my 2 cents, if/when this is implemented in the future, I think it would be useful to add control over the number of worker threads being spawned, instead of only having either one or unlimited threads as options.

    For example, think about a function or block of code being executed on a list of input items (files, strings, urls...) Right now the options are:

    1. use a simple for/while loop: this uses a single thread (the main thread) and can be slow if there are many items and each operation has some intrinsic latency (NFS, curl, whatever), which is why people ask for parallelism in the shell;
    2. spawn each item into the background, as if using & naively: this would spawn an unlimited number of worker threads or processes (one per item) which is usually a bad idea;
    3. use GNU parallel, xargs -P, or some other subprocess orchestrator: these are mature and stable options, but they are not integrated in the language and hence suffer from "quoting hell"

    As far as syntax, I can see two options:

    1. Implicit parallelism: add an option to for and while to specify the number of parallel threads that will be spawned to execute the body, for example right after the main keyword, in order not to break existing scripts:
    for -j8 url in $urls
        curl $url ... | something | ...
    end

    Example with while:

    curl ... | while -j8 read one two three
        handle $one ... | some $two | ...
    end
    1. Explicit parallelism: add a parallel operator (which could be & or something else) and a join operation (wait or something else) and allow specifying the size of the thread pool, and maybe even which thread pool to use.

    If the parallel operator is a keyword to put in front of a command or block (much like go is used in the Go language) then it could accept the same -j option as for and while. In fact, the keyword begin itself could accept the -j option in order to execute its contents in the background (but it's a bit cryptic, so maybe a dedicated keyword would be better in this case?)

    while ...
        ...
        begin -j8 -nfoo
            # this block will be executed in the background
            # by a pool of 8 threads named "foo"
        end
        ...
    end
    ...
    # wait for all threads in the "foo" pool to complete
    wait -nfoo

    The implied semantics in all of these cases is that when the pool is full, the next for body, while body, or explicit background operator will block, waiting for a worker thread to get free. Also, in the case of implicit parallelism, the end of the parallel loop will wait for all threads to complete, while in the case of explicit parallelism, it's left to the user.

    As for the option name, make and parallel use -j (jobs) while xargs uses -P (processes)

  25. maxnordlund commented on Feb 12, 2026

    @maxnordlund
    Contributor

    You can mostly get away with it today with a bit of clever use of $last_pid and wait, like this:

    function in-parallell -a in_flight -a command
        set -l jobs
    
        for arg in $argv[3..]
            if test (count $jobs) -gt $in_flight
                wait --any $jobs &>/dev/null
                set in_flight (math $in_flight + 1)
            end
    
            fish -c $command $arg &
            set -a jobs $last_pid
        end
    
        wait $jobs &>/dev/null
    end

    And use it like this:

    in-parallell 4 'sleep 5; echo hello $argv' jane joe world (seq 10)

    It's a bit sloppy, but it does work. You could imagine replacing the fish -c ... & with just eval ... & or even $command .. &. It does highlight a few more things though. First, I use $last_pid but one would think I could have just as easily used (jobs | cut -f1). However wait does not accept job ids, only pids. This would need to change as jobs would be either a process or a thread (or some equivalent). (Yes I know about jobs -p, that wasn't the point.)

    wait also accepts a string to match the command, i.e. wait sleep waits for all sleep processes running in the background. jobs shows each process group, which all differ. If it was possible to select which process group a job runs in, for example ... & 96677, and select what to wait based on the group, wait -g 96677, then that would open up a lot of possibilities. I suspect however it is used to isolate jobs, in which case you'd need some fish only grouping.

    This thread has focused a lot on &, but there are more places where fish code should run concurrently. Take foo (bar | psub), psub creates a pipe and prints it's path so it becomes foo /tmp/.../mypipe, then runs cat /tmp/.../mypipe &. All good right? Well if both foo and bar are functions this becomes interesting because only one can run at a time. Thus the cat & effectively runs in the foreground. In an ideal world every command substitution runs concurrently.

    The biggest drawback with this, even if you could run functions in the background, is that there's no inline functions/code block parameters. Perhaps a small price to pay, but it gives incentive to make & usable with language constructs.

  26. acidnik commented on Oct 10, 2026

    @acidnik

    it's such a shame that this core functionality that is expected from a shell is still not implemented. i was really hoping that rust port will help move it forward

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions