2
votes

I'm using Julia v0.4.5 and have this simple julia script to subscribe from redis channel:

using Redis

subHandler(x) = print(x)
errHandler(err) = print(err)

redisConn = RedisConnection(host="127.0.0.1", port=6379, db=0)
flushall(redisConn)

subConn = open_subscription(redisConn, errHandler)
subscribe(subConn, "julia-channel", subHandler)

If I type this script line by line in Julia repl, it works as expected.
However, if I put this code into a script file and run from shell:

julia sub.jl

Julia exits with nothing printed in a few seconds..
Maybe I should put the subscription into some kind of thread or loop (to keep julia running)?

1
println(subscribe(subConn, "julia-channel", subHandler))? - python必须死
I would guess that @FGFW is on the right track. You're probably just seeing the output of the last line when running in REPL (which is equivalent to calling display on the last line). If you want the script to be interactive, you will need to add that to your script! - Daniel Arndt
@FGFW println(subscribe(subConn, "julia-channel", subHandler)) prints '47' on terimal and julia still exits. - xiedidan
@DanielArndt In repl, the last line doesn't print anything. When there's data published on the subscribed channel, subHandler (not subscribe()) prints subscribed data. According to redis.jl readme, subscribe() "spawns a routine that runs in the background to process events received from the server". Thus I guess the background routine should keep julia running, but that's not true... - xiedidan
Ahh, that makes sense. Julia definitely won't keep itself alive for background tasks, this has caused some strange "pipe closed" issues for me in the past, particularly in tests when I try printing things. - Daniel Arndt

1 Answers

2
votes

Inspired by FGFW and DanielArndt, I just found the answer.
In short, after subscribe(), adding the following code to keep julia run:

while (true)
  sleep(1)
end

Explanation:
According to redis.jl readme, subscribe() spawns a background routine to handle server publish events. However, in script mode, julia main thread(routine) exits after subscribe(), so that background routine is also terminated. The while - sleep loop prevents main loop from exiting.
Repl maintains user interactive loop, so we don't have to loop by hand.