Created
September 6, 2014 14:21
-
-
Save maliubiao/0872c5fb9620a981aa6e to your computer and use it in GitHub Desktop.
replace the log file on the fly
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#-*-encoding=utf-8-*- | |
import gdb | |
import os | |
import pdb | |
import os.path | |
S_IRUSR = 0400 | |
S_IWUSR = 0200 | |
S_IXUSR = 0100 | |
S_IRGRP = S_IRUSR >> 3 | |
S_IWGRP = S_IWUSR >> 3 | |
S_IXGRP = S_IXUSR >> 3 | |
S_IROTH = S_IRGRP >> 3 | |
S_IWOTH = S_IWGRP >> 3 | |
S_IXOTH = S_IXGRP >> 3 | |
O_RDONLY = 00 | |
O_WRONLY = 01 | |
O_RDWR = 02 | |
O_CREAT = 0100 | |
O_EXCL = 0200 | |
O_NOCTTY = 0400 | |
O_TRUNC = 01000 | |
O_APPEND = 02000 | |
O_NONBLOCK = 04000 | |
O_SYNC = 04010000 | |
O_ASYNC = 020000 | |
O_LARGEFILE = 0100000 | |
O_DIRECTORY = 0200000 | |
O_NOFOLLOW = 0400000 | |
O_CLOEXEC = 02000000 | |
O_DIRECT = 040000 | |
O_NOATIME = 01000000 | |
O_DSYNC = 010000 | |
O_TMPFILE = 020200000 | |
def find_log_fd(pid, log): | |
fd_dir = "/proc/%d/fd" % pid | |
for i in os.listdir(fd_dir): | |
if os.readlink(os.path.join(fd_dir, i)) == log: | |
return int(i) | |
raise IOError("unable to find the log fd") | |
def replace_log(info): | |
gdb.execute("attach %d" % info["pid"], to_string=True) | |
fd = find_log_fd(info["pid"], info["log"]) | |
func_open = 'call open("%s", %d, %d)' % (info["newlog"], info["flags"], info["mode"]) | |
fdstr = gdb.execute(func_open, to_string=True) | |
newfd = int(fdstr.split("=")[1].strip()) | |
func_dup2 = "call dup2(%d, %d)" % (newfd, fd) | |
gdb.execute(func_dup2, to_string=True) | |
gdb.execute("call close(%d)" % (newfd), to_string=True) | |
gdb.execute("detach") | |
""" | |
def test(pid): | |
replace_log({ | |
"pid": pid, | |
"log": "/data/project/py/github/gist/log", | |
"newlog": "/data/project/py/github/gist/newlog", | |
"flags": O_CREAT | O_SYNC | O_RDWR |O_TRUNC, | |
"mode": S_IWUSR|S_IRUSR | |
}) | |
test(15508) | |
""" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <unistd.h> | |
#include <sys/stat.h> | |
#include <fcntl.h> | |
#include <sys/types.h> | |
char *msg[] = {"test\n"}; | |
int main(int argc, char **argv) | |
{ | |
int fd; | |
fd = open("log", O_CREAT|O_TRUNC|O_SYNC|O_RDWR, S_IWUSR|S_IRUSR); | |
if (fd < 0) { | |
printf("open log failed\n"); | |
exit(0); | |
} | |
printf("pid: %d\n", getpid()); | |
while(1) { | |
sleep(2); | |
write(fd, *msg, strlen(*msg)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment