0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

nohupの使い方

Posted at

nohupとは

nohup は、SSH接続を切断してもコマンドを実行し続けるためのLinux/Unixコマンドです。サーバー上で長時間かかる処理(バッチ、学習処理、ログ解析など)を実行する際によく使われます。

接続元のターミナル(SIGHUP)が切れてもプロセスが終了しない点が最大の特徴です。


基本構文

nohup コマンド &
  • nohup:ハングアップを無視
  • &:バックグラウンド実行

標準出力と標準エラー出力は、デフォルトで nohup.out にリダイレクトされます。


基本的な使用例

1. Pythonスクリプトをバックグラウンドで実行

nohup python app.py &

実行後、以下のようなメッセージが表示されます。

nohup: ignoring input and appending output to 'nohup.out'

2. 出力ファイルを指定する

nohup python app.py > app.log 2>&1 &
  • >:標準出力
  • 2>&1:標準エラーも同じファイルへ

3. 入力を完全に無効化する

nohup コマンド < /dev/null > out.log 2>&1 &

対話入力が不要な処理に向いています。


実行中プロセスの確認

ps aux | grep app.py

または

jobs

プロセスを停止する方法

PIDを指定して停止

kill PID

強制終了の場合

kill -9 PID

nohup.out の確認

cat nohup.out
tail -f nohup.out

リアルタイムでログを追いたい場合は tail -f が便利です。


よくある注意点

  • nohup 単体ではバックグラウンドにならない(& が必要)
  • カレントディレクトリに nohup.out が作成される
  • SSH切断後も動作するが、サーバー再起動では停止する

nohup と screen / tmux の違い

項目 nohup screen / tmux
接続切断耐性
再接続 ×
操作の柔軟性
学習コスト

単純な常駐処理は nohup、作業再開が必要な場合は tmuxscreen が向いています。


まとめ

  • nohup はSSH切断後も処理を継続したいときに有効
  • & と出力リダイレクトを忘れない
  • ログ管理を意識して使うと運用が楽になる

サーバー作業の基本コマンドとして、覚えておくと非常に便利です。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?