mue*_*bau 7 c linux segmentation-fault pty
我在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);
}
Run Code Online (Sandbox Code Playgroud)
但它适用于:
fprintf(stderr, "hello\n");
Run Code Online (Sandbox Code Playgroud)
是什么造成的?
NoD*_*und 10
你有一个段错误,因为它fd是一个int,fprintf除了一个FILE*.
fd = posix_openpt(O_RDWR | O_NOCTTY);
fprintf(fd, "hello\n");
close(fd);
Run Code Online (Sandbox Code Playgroud)
尝试fdopen在这fd:
FILE* file = fdopen(fd, "r+");
if (NULL != file) {
fprintf(file, "hello\n");
}
close(fd);
Run Code Online (Sandbox Code Playgroud)