[英]segmentation fault on pseudo terminal
I get a segmentation fault with this code on fprintf: 我在fprintf上使用此代码得到了分段错误:
#define _GNU_SOURCE
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <stdint.h>
#include <fcntl.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <unistd.h>
int fd;
int main(int argc, char **argv) {
fd = posix_openpt(O_RDWR | O_NOCTTY);
fprintf(fd, "hello\n");
close(fd);
}
But it works fine with: 但它适用于:
fprintf(stderr, "hello\n");
What is causing this? 是什么造成的?
You have a segfault, because fd
is an int
, and fprintf
except of a FILE*
. 你有一个段错误,因为
fd
是一个int
,而fprintf
除了一个FILE*
。
fd = posix_openpt(O_RDWR | O_NOCTTY);
fprintf(fd, "hello\n");
close(fd);
Try fdopen over that fd
: 尝试fdopen over
fd
:
FILE* file = fdopen(fd, "r+");
if (NULL != file) {
fprintf(file, "hello\n");
}
close(fd);
To write out to a file descriptor use write()
. 要写出文件描述符,请使用
write()
。 The fprintf
command requires a FILE*
typed pointer. fprintf
命令需要一个FILE*
类型指针。
#define _XOPEN_SOURCE 600
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main(void)
{
int result = EXIT_SUCCESS;
int fd = posix_openpt(O_RDWR | O_NOCTTY);
if (-1 == fd)
{
perror("posix_openpt() failed");
result = EXIT_FAILURE;
}
else
{
char s[] = "hello\n";
write(fd, s, strlen(s));
close(fd);
}
return result;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.