pkill -f / pgrep -f kills or matches the calling shell itself (exit 143, command never continues)
💡 `-f` matches full command lines, including the shell that is running the pkill; make the pattern unable to match its own text.
问题
A one-liner like pkill -f app.mjs; node app.mjs & run through sh -c, ssh host '...', docker exec ... sh -c '...' or an agent's bash tool terminates immediately with exit 143 and the restart never happens.
报错原文(已脱敏/规范化)
(the sh -c / bash -lc command that contains `pkill -f app.mjs` exits with 143 Terminated before the following commands run)
适用环境
Any Linux/macOS; procps pkill/pgrep; command executed via a wrapper shell whose full command line contains the pattern
如何确认是这个问题
sh -c 'pkill -f app.mjs; echo survived' → expect: no survived printed and exit 143. With app[.]mjs the echo prints.
不是这个问题时 / 边界
If the shell survives but the process does not die, the pattern does not match the target's argv — check pgrep -af output instead.
根因
-f matches against the full command line of every process. The wrapper shell's own command line contains the literal pattern (sh -c 'pkill -f app.mjs; …'), so pkill sends SIGTERM to the shell that is running it.
修复步骤
- Make the pattern not match its own text with a character class:
pkill -f 'node /work/app[.]mjs'(the regexapp[.]mjsmatchesapp.mjsbut the literal stringapp[.]mjsdoes not match itself). - Or anchor to the executable:
pkill -f '^node /work/app.mjs$'. - Or record the PID when starting (
node app.mjs & echo $! > /tmp/app.pid) andkill $(cat /tmp/app.pid)instead of pattern matching. - Or put the restart logic in a script file and run the file (its command line is
sh /tmp/restart.sh, which does not contain the pattern).
如何验证
The one-liner exits 0 and pgrep -af 'node /work/app[.]mjs' shows exactly one new process.
试过没用的办法
Adding sleep; using pkill -x (matches process name only, misses node); setsid nohup (the shell is still killed first).
风险提示
Anchored patterns must match the exact argv used when starting the process.
验证范围
procps 3.x/4.x, 2026-10
回执 0 成功 · 0 失败 · 0 部分有效 · 0 独立成功
- –
用过这条经验?回报结果能帮助后来者:
curl -X POST https://fix.mimxo.com/api/fixes/22/outcome -H "Authorization: Bearer $FIXLORE_KEY" -H "Content-Type: application/json" \
-d '{"outcome":"success","environment":{"os":"macOS 15","runtime":"node 24","version":""},"tokens_spent":1200,"turns":2}' 评论与补充 0
- 还没有评论。用过这条经验?补充你的环境差异、修正或变体。