Skip to content

Instantly share code, notes, and snippets.

@4ge32
Created October 22, 2018 00:58
Show Gist options
  • Save 4ge32/374866765ae023e533968b18a52085f8 to your computer and use it in GitHub Desktop.
Save 4ge32/374866765ae023e533968b18a52085f8 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE 1
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define PATH_MAX 256
static int write_to_tmpfile(int fd)
{
const char *buf = "My test for tmpfile method!";
ssize_t ret;
ssize_t len;
len = strlen(buf);
if (write(fd, buf, len) < 0) {
perror("write");
return -1;
}
return 0;
}
static int read_from_tmpfile(int fd)
{
char buf[256];
ssize_t ret;
ssize_t len;
len = sizeof(buf);
while ((ret = read(fd, buf, len)) != 0) {
printf("ret %d\n", ret);
if (ret == -1) {
if (errno == EINTR)
continue;
perror("read");
return -1;
}
if (write(STDOUT_FILENO, buf, ret) < 0) {
perror("write");
return -1;
}
}
return 0;
}
static int linkat_tmpfile(int fd)
{
char path[PATH_MAX];
pid_t pid;
pid = getpid();
snprintf(path, PATH_MAX, "/proc/%d/fd/%d", pid, fd);
linkat(AT_FDCWD, path, AT_FDCWD, path, AT_SYMLINK_FOLLOW);
return 0;
}
int main(int argc, char *argv[])
{
int tmp_fd;
int len;
char buf[256];
if (argc != 2) {
fprintf(stderr, "usage: %s DirectoryPath\n", argv[0]);
}
if (tmp_fd = open(argv[1] , O_TMPFILE | O_WRONLY, 0660) < 0) {
perror("error: open");
fprintf(stderr, "make sure that whether %s is directory path\n", argv[1]);
return tmp_fd;
}
printf("tmp_fd %d\n", tmp_fd );
if (write_to_tmpfile(tmp_fd) < 0)
goto out;
if (read_from_tmpfile(tmp_fd) < 0)
goto out;
printf("A temporary file is created.\n");
printf("Press enter key when killing this process.\n");
//len = read(STDIN_FILENO, buf, sizeof(buf));
//if (len < 0)
// perror("error: read ");
out:
close(tmp_fd);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment