简体   繁体   English

伪终端的分段故障

[英]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);

You are trying to pass the file descriptor (used for low-level file access) to fprintf , but it actually needs a FILE structure, defined in stdio.h . 您正在尝试将文件描述符(用于低级文件访问)传递给fprintf ,但它实际上需要一个在stdio.h定义的FILE结构。

You could use dprintf or fdopen (which are POSIX). 你可以使用dprintffdopen (它们是POSIX)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM