Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

segmentation fault on pseudo terminal

I get a segmentation fault with this code on 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?

like image 440
muebau Avatar asked Sep 01 '14 14:09

muebau


3 Answers

You have a segfault, because fd is an int, and fprintf except of a FILE*.

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

Try fdopen over that fd:

FILE* file = fdopen(fd, "r+");
if (NULL != file) {
  fprintf(file, "hello\n");    
}
close(fd);
like image 170
NoDataFound Avatar answered Nov 19 '22 07:11

NoDataFound


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.

You could use dprintf or fdopen (which are POSIX).

like image 37
Jay Avatar answered Nov 19 '22 05:11

Jay


To write out to a file descriptor use write(). The fprintf command requires a FILE* typed pointer.

#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;
}
like image 3
alk Avatar answered Nov 19 '22 06:11

alk