伪终端的分段故障

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)


Jay*_*Jay 5

您正尝试将文件描述符(用于低级文件访问)传递给fprintf,但它实际上需要一个FILE定义的结构stdio.h.

你可以使用 dprintffdopen(它们是POSIX).