//----------------------------------------------------------------- // tryfork.s // // This example uses the 'fork' and 'waitpid' system-calls. // // to assemble: $ as tryfork.s -o tryfork.o // and to link: $ ld tryfork.o base10io.o -o tryfork // // programmer: ALLAN CRUSE // written on: 07 FEB 2007 //----------------------------------------------------------------- # manifest constants .equ STDOUT, 1 # device-file ID-number .equ sys_EXIT, 1 # system-call ID-number .equ sys_FORK, 2 # system-call ID-number .equ sys_WRITE, 4 # system-call ID-number .equ sys_WAITPID, 7 # system-call ID-number .equ sys_GETPID, 20 # system-call ID-number .section .data msg1: .ascii " parent-process is " # explanation of info buf1: .ascii " \r\n" # contained in buffer len1: .int . - msg1 # size of the message msg2: .ascii " child-process is " # explanation of info buf2: .ascii " \r\n" # contained in buffer len2: .int . - msg2 # size of the message pid: .int 0 # storage for the PID .section .text _start: # use the 'fork' system-call to create a child-process mov $sys_FORK, %eax # system-call ID-number int $0x80 # request kernel service mov %eax, pid # store the return-value # at this point our program has two branches or %eax, %eax # process is the child? jz nowait # yes, bypass 'waitpid' # parent-process waits for child-process to finish mov %eax, %ebx # child's PID into EBX xor %ecx, %ecx # discard child-status xor %edx, %edx # use default behavior mov $sys_WAITPID, %eax # system-call ID-number int $0x80 # request kernel service nowait: # both processes execute the remainder of this program lea buf1, %edi # buffer-address in EDI lea msg1, %ecx # string-address in ECX mov len1, %edx # string-length in EDX cmp $0, pid # process is parent? jnz bufok # yes, keep the values lea buf2, %edi # buffer-address in EDI lea msg2, %ecx # string-address in ECX mov len2, %edx # string-length in EDX bufok: # the process formats its PID in its message-buffer mov $sys_GETPID, %eax # system-call ID-number int $0x80 # request kernel service call eax2asc # convert PID to string # the process writes its message to the terminal screen mov $sys_WRITE, %eax # system-call ID-number mov $STDOUT, %ebx # defive-file ID-number int $0x80 # request kernel service # finally the process terminates mov $sys_EXIT, %eax # system-call ID-number xor %ebx, %ebx # use zero as exit-code int $0x80 # request kernel service .global _start # make entry-point visible .end # nothing more to assemble