|
| 1 | +; Mostly an example of the fork API, also uses waitpid and execve for better illustration |
| 2 | +; API calls found in this example program: |
| 3 | +; fork, waitpid, execve, write, exit |
| 4 | +; High level description of what theis example program does: |
| 5 | +; Forks |
| 6 | +; The parent waits for the child and prints a message when done |
| 7 | +; prints a message and then executes /bin/ps before returning to parent |
| 8 | + |
| 9 | + |
| 10 | +section .text |
| 11 | +global _start |
| 12 | + |
| 13 | +_start: |
| 14 | + |
| 15 | +; Fork |
| 16 | +;------------------------------------------------------------------------------ |
| 17 | + mov eax, 2 ; fork() |
| 18 | + int 0x80 |
| 19 | + ; Return on failure is -1 |
| 20 | + ; Return is 0 if child |
| 21 | + ; Return is the pid of child if parent |
| 22 | + cmp eax, 0 ; Compare to child value |
| 23 | + jz child ; Go to child process if so |
| 24 | + |
| 25 | +parent: ; otherwise your the parent with pid of child in eax |
| 26 | + ; Wait for child |
| 27 | + mov ebx, eax ; Get that pid into ebx, we need it |
| 28 | + mov eax, 7 ; waitpid() |
| 29 | + int 0x80 |
| 30 | + |
| 31 | + ; Let STDOUT know you're the parent |
| 32 | + mov eax, 4 ; write() |
| 33 | + mov ebx, 1 ; STDOUT |
| 34 | + mov ecx, parent_msg ; Message for parent |
| 35 | + mov edx, 11 ; Message length |
| 36 | + int 0x80 |
| 37 | + |
| 38 | + ; Bail |
| 39 | + jmp exit |
| 40 | + |
| 41 | +child: |
| 42 | + ; Let STDOUT know you're the child |
| 43 | + mov eax, 4 ; write() |
| 44 | + mov ebx, 1 ; STDOUT |
| 45 | + mov ecx, child_msg ; Message for child |
| 46 | + mov edx, 10 ; Message length |
| 47 | + int 0x80 |
| 48 | + |
| 49 | + ; Execute a shell command |
| 50 | + mov eax, 11 ; execve() |
| 51 | + mov ebx, command ; command to execute |
| 52 | + mov ecx, args ; arguments (none) |
| 53 | + mov edx, env ; enviornment (none) |
| 54 | + int 0x80 |
| 55 | + |
| 56 | + ; Bail (but parent waiting on this) |
| 57 | + jmp exit |
| 58 | + |
| 59 | + |
| 60 | +; Exit |
| 61 | +;------------------------------------------------------------------------------ |
| 62 | + exit: |
| 63 | + mov eax, 1 ; exit |
| 64 | + mov ebx, 0 ; null argument to exit |
| 65 | + int 0x80 |
| 66 | + |
| 67 | +section .data |
| 68 | + child_msg db 'Ima Child', 0x0a |
| 69 | + parent_msg db 'Ima Parent', 0x0a |
| 70 | + command db '/bin/ps', 0x00 |
| 71 | + args dd command |
| 72 | + env db 0x00,0x00,0x00,0x00 |
0 commit comments