这是我的程序foo.c
。
#include <stdio.h>
#include <unistd.h>
int main()
{
int i;
printf("foon");
write(0, "barn", 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("foon") != 4)
fprintf(stderr, "Failed to write 4 bytes to standard outputn");
if (write(0, "barn", 4) != 4)
fprintf(stderr, "Failed to write 4 bytes to standard inputn");
return 0;
}
,然后运行它与make bg
,然后我得到:
$ make bg
gcc foo.c
./a.out &
sleep 1
Failed to write 4 bytes to standard input
foo
$