Fork: Difference between revisions
Content added Content deleted
(Add BaCon) |
No edit summary |
||
Line 1,277: | Line 1,277: | ||
=={{header|X86 Assembly}}== |
=={{header|X86 Assembly}}== |
||
I've written a subroutine that prints out any positive value. It lives on my desktop and you can't find it on rosetta code. |
|||
{{works with|NASM|Linux}}<br> |
|||
I've also written a sleep subroutine and you can find that in the Sleep task on this site. |
|||
While it IS possible to use native syscalls to create forks, it's not recommended. sys_fork requires manual setup for the pt_regs structure. It further requires you to enter kernal space using sysenter/exit pairs, setup the registers then call sys_fork. Linking to the C library is simply less work for user space forks. The only time it's really used is during debugging applications. |
|||
<lang asm> |
|||
<lang x86asm> |
|||
extern fork |
|||
; x86_64 linux nasm |
|||
extern printf |
|||
%include "/home/james/Desktop/ASM_LIB/Print.asm" |
|||
%include "/home/james/Desktop/ASM_LIB/Sleep.asm" |
|||
section .text |
|||
global _start |
|||
_start: |
|||
call fork |
|||
cmp eax, 0 |
|||
je _child |
|||
jg _parent |
|||
jmp _exit |
|||
_parent: |
|||
push p_msg |
|||
call printf |
|||
jmp _exit |
|||
_child: |
|||
push c_msg |
|||
call printf |
|||
jmp _exit |
|||
_exit: |
|||
push 0x1 |
|||
mov eax, 1 |
|||
push eax |
|||
int 0x80 |
|||
ret |
|||
section .data |
section .data |
||
c_msg db "Printed from Child process",13,10,0 |
|||
parent: db "Parent: " |
|||
child: db "Child: " |
|||
newLine: db 10 |
|||
section .text |
|||
global _start |
|||
_start: |
|||
mov rax, 57 ; fork syscall |
|||
syscall |
|||
cmp rax, 0 ; if the return value is 0, we're in the child process |
|||
je printChild |
|||
printParent: ; else it's the child's PID, we're in the parent |
|||
mov rax, 1 |
|||
mov rdi, 1 |
|||
mov rsi, parent |
|||
mov rdx, 8 |
|||
syscall |
|||
mov rax, 39 ; sys_getpid |
|||
syscall |
|||
mov rdi, rax |
|||
call Print_Unsigned |
|||
mov rax, 1 |
|||
mov rdi, 1 |
|||
mov rsi, newLine |
|||
mov rdx, 1 |
|||
syscall |
|||
mov rdi, 1 ; sleep so the child process can print befor the parent exits |
|||
call Sleep ; you might not see the child output if you don't do this |
|||
jmp exit |
|||
printChild: |
|||
mov rdi, 1 |
|||
call Sleep ; sleep and wait for parent to print to screen first |
|||
mov rax, 1 |
|||
mov rdi, 1 |
|||
mov rsi, child |
|||
mov rdx, 7 |
|||
syscall |
|||
mov rax, 39 ; sys_getpid |
|||
syscall |
|||
mov rdi, rax |
|||
call Print_Unsigned |
|||
mov rax, 1 |
|||
mov rdi, 1 |
|||
mov rsi, newLine |
|||
mov rdx, 1 |
|||
syscall |
|||
exit: |
|||
mov rax, 60 |
|||
mov rdi, 0 |
|||
syscall |
|||
</lang> |
</lang> |
||