我正試圖編寫一個程序來追蹤系統調用。我做這項工作很困難。我試着調用一個fork()來創建自己的一個實例(代碼),然後監視生成的子進程。如何跟蹤系統調用的進程?
目標是讓父進程返回子進程所做的每個系統調用的索引並將其輸出到屏幕。不知何故,它不按計劃運作。
下面是代碼:
#include <unistd.h> /* for read(), write(), close(), fork() */
#include <fcntl.h> /* for open() */
#include <stdio.h>
#include <sys/ptrace.h>
#include <sys/reg.h>
#include <sys/wait.h>
#include <sys/types.h>
int main(int argc, char *argv[]) {
pid_t child;
long orig_eax;
child = fork();
if (0 == child)
{
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
if (argc != 3) {
fprintf(stderr, "Usage: copy <filefrom> <fileto>\n");
return 1;
}
int c;
size_t file1_fd, file2_fd;
if ((file1_fd = open(argv[1], O_RDONLY)) < 0) {
fprintf(stderr, "copy: can't open %s\n", argv[1]);
return 1;
}
if ((file2_fd = open(argv[2], O_WRONLY | O_CREAT)) < 0) {
fprintf(stderr, "copy: can't open %s\n", argv[2]);
return 1;
}
while (read(file1_fd, &c, 1) > 0)
write(file2_fd, &c, 1);
}
else
{
wait(NULL);
orig_eax = ptrace (PTRACE_PEEKUSER, child, 4 * ORIG_EAX, NULL);
printf("copy made a system call %ld\n", orig_eax);
ptrace(PTRACE_CONT, child, NULL, NULL);
}
return 0;
}
該代碼是基於這樣的代碼:
#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <linux/user.h> /* For constants
ORIG_EAX etc */
int main()
{
pid_t child;
long orig_eax;
child = fork();
if(child == 0) {
ptrace(PTRACE_TRACEME, 0, NULL, NULL);
execl("/bin/ls", "ls", NULL);
}
else {
wait(NULL);
orig_eax = ptrace(PTRACE_PEEKUSER,
child, 4 * ORIG_EAX,
NULL);
printf("The child made a "
"system call %ld\n", orig_eax);
ptrace(PTRACE_CONT, child, NULL, NULL);
}
return 0;
}
這一個的輸出是:
The child made a system call 11
這對於索引執行系統調用。
按照手冊頁的wait():
All of these system calls are used to wait for state changes in a child
of the calling process, and obtain information about the child whose
state has changed. A state change is considered to be: the child terminated;
the child was stopped by a signal; or the child was resumed by
a signal.
我的理解是,每一個系統調用是由用戶程序調用時,內核將首先檢查過程是否存在方式在執行系統調用例程之前跟蹤並用信號暫停該過程並將控制返回給父系。這不會是狀態變化嗎?
「不知怎的,它沒有按計劃進行工作。」謹慎闡述?你期望發生什麼,實際發生了什麼?請編輯問題以添加它,而不是作爲評論。 –
此外,你在父進程中做的第一件事是調用'wait'。這個函數完全是這樣的,等到子進程結束,這意味着'ptrace'調用嘗試跟蹤一個不再存在的進程。 –
[推薦] [1]我想,這可能會有所幫助。 [1]:http://stackoverflow.com/questions/6468896/why-is-orig-eax-provided-in-addition-to-eax –