当通过Makefile在后台运行程序时,为什么write()调用不在终端上显示输出?
问题描述:
这是我的程序foo.c
。当通过Makefile在后台运行程序时,为什么write()调用不在终端上显示输出?
#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
printf("foo\n");
write(0, "bar\n", 4);
return 0;
}
foo
都和bar
被印刷在终端上,如果我在运行前景或背景的程序。
$ gcc foo.c
$ ./a.out
foo
bar
$ ./a.out &
[1] 2081
$ foo
bar
[1]+ Done ./a.out
但是当我通过Makefile
运行程序时,我看到正在打印bar
程序在前台运行,只有当。当程序在后台运行时,它不会打印在终端上。
以下是我的Makefile
的外观。
fg:
gcc foo.c
./a.out
sleep 1
bg:
gcc foo.c
./a.out &
sleep 1
这里是输出。
$ make fg
gcc foo.c
./a.out
foo
bar
sleep 1
$ make bg
gcc foo.c
./a.out &
sleep 1
foo
$
程序在后台经由Makefile
运行时为什么不打印在终端上bar
?
答
您的程序正在写入标准输入与write()
系统调用。不能保证你能做到这一点,也不能保证当你这样做时,它会出现在终端上。
最有可能的是,make
提供/dev/null
作为标准输入,所以当你的程序试图写入它时,它可能会失败(未打开写入)或成功写入黑洞。
当我修改在foo.c
代码为:
#include <stdio.h>
#include <unistd.h>
int main(void)
{
if (printf("foo\n") != 4)
fprintf(stderr, "Failed to write 4 bytes to standard output\n");
if (write(0, "bar\n", 4) != 4)
fprintf(stderr, "Failed to write 4 bytes to standard input\n");
return 0;
}
,然后用make bg
运行它,然后我得到:
$ make bg
gcc foo.c
./a.out &
sleep 1
Failed to write 4 bytes to standard input
foo
$
+0
确实,这是我的程序中的错误,如果我修改'write(0)'写入(1),问题就解决了,现在我看到'foo'和'bar' make bg'。谢谢! –
'写(0,'你确定你正在编写'stdout'? –