Skip to content

Instantly share code, notes, and snippets.

@rocallahan
Created November 29, 2016 20:34
Show Gist options
  • Save rocallahan/6b557e6f0a63bf00b586f58187af8927 to your computer and use it in GitHub Desktop.
Save rocallahan/6b557e6f0a63bf00b586f58187af8927 to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE 1
#define _POSIX_SOURCE 2
#include <fcntl.h>
#include <unistd.h>
#include <assert.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/fcntl.h>
#include <sys/syscall.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <stdio.h>
#define FILENAME "foo.txt"
int main(void) {
int fd, err, i, status;
pid_t pid;
size_t pagesize = sysconf(_SC_PAGESIZE);
fd = open(FILENAME, O_CREAT | O_EXCL | O_RDWR, 0600);
assert(fd >= 0);
unlink(FILENAME);
/* Write a page's worth of data. */
for (i = 0; i < pagesize / sizeof(i); ++i) {
ssize_t nwritten = write(fd, &i, sizeof(i));
assert(nwritten == sizeof(i));
}
struct flock64 lock = {
.l_type = F_WRLCK, .l_whence = SEEK_SET, .l_start = 0, .l_len = pagesize
};
lock.l_type = F_WRLCK;
err = fcntl(fd, F_SETLK64, &lock);
assert(0 == err);
if (0 == (pid = fork())) {
/* ptrace(PTRACE_TRACEME, 0, 0, 0);
raise(SIGSTOP); */
signal(SIGPWR, SIG_IGN);
lock.l_type = F_RDLCK;
err = fcntl(fd, F_GETLK64, &lock);
assert(0 == err);
lock.l_type = F_RDLCK;
lock.l_pid = 0;
err = fcntl(fd, F_SETLKW64, &lock);
assert(0 == err);
lock.l_type = F_UNLCK;
fcntl(fd, F_SETLK64, &lock);
return 0;
}
/* assert(pid == waitpid(pid, &status, __WALL));
assert(WIFSTOPPED(status) && WSTOPSIG(status) == SIGSTOP);
ptrace(PTRACE_CONT, pid, 0, 0); */
usleep(500000);
kill(pid, 30);
/* assert(pid == waitpid(pid, &status, __WALL)); */
usleep(500000);
/* ptrace(PTRACE_SYSCALL, pid, 0, 0);
assert(pid == waitpid(pid, &status, __WALL)); */
lock.l_type = F_UNLCK;
fcntl(fd, F_SETLK64, &lock);
/* ptrace(PTRACE_CONT, pid, 0, 0); */
waitpid(pid, &status, 0);
assert(WIFEXITED(status) && 0 == WEXITSTATUS(status));
printf("Success!\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment