下面的2个程序,echo.c循环的从标准输入读取一行字符串,写入echo.txt文件,popen.c用popen(
)
打开echo的标准输入,每秒向其写入一行字符串。
当popen.c顺利执行的话,cat echo.txt可以看到文件有内容;但是用ctrl +
c中断popen程序的话,
无论在信号处理函数中是否向管道写入内容,或者用pcolse关闭管道,cat
echo.txt不会有内容。
能不能在有中断信号的情况下也能让子进程正确写入数据到echo.txt。
======== popen.c ========
// compile: c99 -Wall -ggdb -o popen popen.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
FILE *write_fd;
static void
term_exit (int sig_num)
{
printf ("get signal
");
fprintf (write_fd, "get signal
");
pclose (write_fd);
exit (0);
}
int
main ()
{
signal (SIGINT, term_exit);
write_fd = popen ("./echo", "w");
for (int i = 0; i < 10; i++)
{
fprintf (write_fd, "line %i
", i);
sleep (1);
}
fprintf (write_fd, "the end
");
pclose (write_fd);
return 0;
}
======== echo.c ========
// compile: c99 -Wall -ggdb -o echo echo.c
#include <stdio.h>
#define BUF_LEN 256
int
main (int argc, char *argv[])
{
char buffer[BUF_LEN];
FILE *fd;
fd = fopen ("echo.txt", "w");
while (fgets (buffer, BUF_LEN, stdin))
{
fputs (buffer, fd);
}
fputs ("echo say: byebye
", fd);
fclose (fd);
return 0;
}