System call can be invoked in application in two different ways. Here to depict this I am writing a C application test.c for both the ways.
Using inline assembly code:
Int this method, you have to know the id of the system call which you would like to invoke. Here in Exercise1, we have added a system call with id: 337, and now I am trying to invoke it in this below example.
- First move the id of system call to the accumulator register (eax).
- Raise an interrupt, for context switch to kernel mode. Here int 0x80 raises a Trap interrupt.
- Now, move the return value into the accumulator.
test.c
_______________________________________________________________________
#include<stdio.h>
int main(){
printf(“Entered main function…!\n”);
/*here starts system call*/
__asm__(“movl $337, %eax”);
__asm__(“int $0x80”);
__asm__(“movl %eax, -4(%ebp)”);
printf(“System call invoked, to see type command: dmesg at your terminal\n”);
printf(“Exiting main….!\n);
return 0;
}
_______________________________________________________________________
Using syscall:
In this we have to include sys/syscall.h header and the code is as follows. mycall is the name of the system call to be invoked, and it is the one we have added in Exercise1.
synatx for syscall :
int syscall(int number, ...);Click here for complete description.
test.c
#include<stdio.h>
#inclide<sys/syscall.h>
int main(){
printf(“Entered main function…!\n”);
/*here starts system call*/
syscall(“SYS_mycall”);
printf(“System call invoked, to see type command: dmesg at your terminal\n”);
printf(“Exiting main….!\n);
return 0;
}
_______________________________________________________________________
Compile and run it.
$ gcc test.c –o test
$ ./test
Entered main function…!
System call invoked, to see type command: dmesg at your terminal
$ dmesg | tail
New sys call invoked by ./test app
Please leave comment :-) Queries are at free of cost
nice explanation .........
ReplyDeletehiiii. The examples are really good. Now i have doubt. In second example we invoked system call by using function "syscall(SYS_mycall)". But i need to pass arguments(let us say int x, int y) to SYS_mycall. how can we acheive that using "syscall" function?
ReplyDeleteThank u.
Example:
Delete#define _GNU_SOURCE
#include
#include
#include
#include
int
main(int argc, char *argv[])
{
pid_t tid;
tid = syscall(SYS_gettid);
syscall(SYS_tgkill, getpid(), tid, SIGHUP);
}
Very Useful. Thank you...
ReplyDelete