以下代码将字符串文字输出到具有匿名和命名流的文件:
#include <fstream>
using namespace std;
int main()
{
ofstream("testfile") << "test" << endl;
ofstream ofs ("testfile2");
ofs << "test2" << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
从strace的输出中可以看到,只有命名的流工作:
open("testfile", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
write(3, "0x400a91\n", 9) = 9
close(3) = 0
open("testfile2", O_WRONLY|O_CREAT|O_TRUNC, 0666) = 3
write(3, "test2\n", 6) = 6
close(3) = 0
Run Code Online (Sandbox Code Playgroud)
此外,如果您使用std :: string而不是文字,则无法编译.
为什么是这样?
我一直在阅读有关EINTR
对write(2)
等,并试图确定是否我需要在我的程序进行检查.作为一个完整性检查,我试图写一个会遇到它的程序.程序永远循环,重复写入文件.
然后,在一个单独的shell中,我运行:
while true; do pkill -HUP test; done
Run Code Online (Sandbox Code Playgroud)
但是,我从test.c看到的唯一输出是.
来自信号处理程序的s.为什么SIGHUP
导致write(2)
失败?
test.c的:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
void hup_handler(int sig)
{
printf(".");
fflush(stdout);
}
int main()
{
struct sigaction act;
act.sa_handler = hup_handler;
act.sa_flags = 0;
sigemptyset(&act.sa_mask);
sigaction(SIGHUP, &act, NULL);
int fd = open("testfile", O_WRONLY);
char* buf = malloc(1024*1024*128);
for (;;)
{
if (lseek(fd, 0, SEEK_SET) == -1)
{
printf("lseek …
Run Code Online (Sandbox Code Playgroud)