为什么当程序在后台通过Makefile运行时,write()调用不在终端上显示输出?



这是我的程序foo.c

#include <stdio.h>
#include <unistd.h>
int main()
{
    int i;
    printf("foon");
    write(0, "barn", 4);
    return 0;
}

如果我在前台或后台运行程序,foobar都在终端上打印。

$ 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
$

最新更新