【发布时间】:2014-04-13 06:25:31
【问题描述】:
请看这段代码。它运行在 CentOS6 64 位。
#include<stdio.h>
int main(int argc, char **argv)
{
fprintf(stderr, "output 1\n");
printf("output 2\n");
fflush(stdout);
system("echo abc");
fprintf(stderr, "output 3\n ");
printf("output 4\n");
fflush(stdout);
daemon(0, 1);
fprintf(stderr, "output 5\n");
printf("output 6\n");
fflush(stdout);
system("echo abc");
fprintf(stderr, "output 7\n");
printf("output 8\n");
fflush(stdout);
}
如果我运行它,我会看到这些消息:
output 1
output 2
abc
output 3
output 4
output 5
output 6
abc
output 7
output 8
如果我使用 ssh 登录并运行它,我会看到相同的结果。
但是,如果我使用二进制名称作为 ssh 的参数并运行它,在调用 daemon(0, 1) 后向 stderr 写入数据时程序会退出。假设二进制名称是 myapp。我跑
ssh localhost myapp
我只会看到这些消息:
output 1
output 2
abc
output 3
output 4
output 5
output 6
abc
有人知道为什么吗?根据调试,程序只有在做了三件事后才退出:
- 调用守护进程(0, 1)。
- 调用系统运行另一个应用程序或 bash 命令。
- 向标准错误写入内容。
非常感谢!
【问题讨论】:
-
在手册页中说,在
dameon程序分叉之后,父级退出,只有子级会看到更多错误。要获得更多调试信息,您可能应该尝试测试函数的返回代码。此外,question 的答案可能有助于获得一些线索(有一部分关于 stdout/stderr 的行为) -
如果你做
ssh localhost 'myapp;sleep 10',你看到所有的输出了吗?ssh服务器在父myapp进程退出后很快退出,因此子进程和任何system()调用之后的任何输出都可能不可见。
标签: c linux unix daemon stderr