Skip to content

Instantly share code, notes, and snippets.

@speters
Created January 26, 2023 12:02
Show Gist options
  • Save speters/2e0b0178d18a24835344faae0678450a to your computer and use it in GitHub Desktop.
Save speters/2e0b0178d18a24835344faae0678450a to your computer and use it in GitHub Desktop.
ftok implementation test
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/stat.h>
void touch(char *file_name) {
FILE *fp;
if ((fp = fopen(file_name, "w")) == NULL) {
perror("fopen");
exit(1);
}
fclose(fp);
}
int main() {
char template[] = "./tmpfileXXXXXX";
int fd;
key_t key;
// Generate the random pathname using mkstemp()
if ((fd = mkstemp(template)) == -1) {
perror("mkstemp");
return 1;
}
printf("Random pathname: %s\n", template);
// Use the key generated by ftok
if ((key = ftok(template, 'R')) == -1) {
perror("ftok");
return 1;
}
printf("%s Key: %d\n", template, key);
// Unlink the file
if (unlink(template) == -1) {
perror("unlink");
return 1;
}
printf("File unlinked\n");
// Touch the file with the same filename
touch(template);
printf("File touched\n");
// Use the key generated by ftok again
if ((key = ftok(template, 'R')) == -1) {
perror("ftok");
return 1;
}
printf("%s Key: %d\n", template, key);
// Close the file descriptor
close(fd);
// Unlink the file
if (unlink(template) == -1) {
perror("unlink");
return 1;
}
printf("File unlinked\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment