Netcat stops when in a detached session

2

1

I want to use netcat to dump a number of blocks of strings to a file. I've been running this in my linux terminal and everything works very well until I try to detach my command line. If I run my command as a detached session netcat stops after the first round of strings.

In short, this works:

nc localhost 3000 > test.txt

But this doesn't:

nc localhost 3000 > test.txt &
[1] 9040
max@starbuck ncats]$ 

[1]+  Stopped                 nc localhost 3000 > test.txt

I suppose this has to do with reaching the end of a send on the server side, but I don't know enough about netcat to tell it, "hey! stay awake until your connection drops"

Ideas? Thanks!!!

Maxwell Bottiger

Posted 2013-03-21T19:36:13.460

Reputation: 33

My guess is that nc is trying to read from its controlling terminal and is getting SIGTTIN and stopping. Does it work if you add </dev/null to the nc command line to tell it to not try to read from standard input? – rra – 2013-03-21T19:53:13.293

Or if you run nc from a screen session? – tink – 2013-03-21T19:54:18.477

adding < /dev/null just causes it to exit immediately. Screen is a possibility, but doesn't explain why this happens. I'll use screen if I can't figure it out. – None – 2013-03-21T20:39:48.620

Answers

1

netcat wants to send its stdin across the socket and print out the response, so it expects to have them both connected and active. I don't know a good way of creating a command that waits forever, but you could try

sleep 86400000 | nc localhost 3000 > test.txt &

Neil

Posted 2013-03-21T19:36:13.460

Reputation: 598

Brilliant! Thank you for the explanation, that makes a lot of sense. It worked perfectly. – Maxwell Bottiger – 2013-03-22T12:50:34.020

1

Some versions of nc support the -d option (noteably the OpenBSD version), which prevents it from trying to read from stdin.

So the code would become:

nc localhost 3000 -d > test.txt &

RBB

Posted 2013-03-21T19:36:13.460

Reputation: 11

This should be the accepted solution – Daniel Alder – 2016-01-09T13:16:54.297