【问题标题】:segmentation fault on pseudo terminal伪终端上的分段错误
【发布时间】:2014-10-25 20:11:36
【问题描述】:

我在 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);
}

但它适用于:

fprintf(stderr, "hello\n");

这是什么原因造成的?

【问题讨论】:

  • 你检查 posix_openpt() 的结果了吗?
  • fprintf() 需要 FILE* 而不是文件描述符
  • 你不应该忽略你不理解的警告......尤其是如果相应的行导致了段错误。

标签: c linux segmentation-fault pty


【解决方案1】:

你有一个段错误,因为fd 是一个int,而fprintf 除了FILE*

fd = posix_openpt(O_RDWR | O_NOCTTY);
fprintf(fd, "hello\n");    
close(fd);

fd 上尝试fdopen

FILE* file = fdopen(fd, "r+");
if (NULL != file) {
  fprintf(file, "hello\n");    
}
close(fd);

【讨论】:

  • 你不是说fdopen(fd, "r+")吗?
  • 没有过多关注O_RDWR,所以这是一个纯粹的错误。谢谢你。我更新了我的答案。
【解决方案2】:

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

您可以使用 dprintffdopen(它们是 POSIX)。

【讨论】:

    【解决方案3】:

    要写入文件描述符,请使用write()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;
    }
    

    【讨论】:

    • 谢谢,但我需要使用 fprintf()。
    猜你喜欢
    • 2014-03-10
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    • 1970-01-01
    • 2019-11-20
    相关资源
    最近更新 更多