logoISU  

CS456 - Systems Programming

Spring 2026

Displaying ./code/nasm/forkexec/forkexec.asm

; Fork and exec
; Compile with: nasm -f elf forkexec.asm
; Link with (64 bit systems require elf_i386 option): ld -m elf_i386 forkexec.o -o forkexec
; or run "make forkexec" since we have a makefile
; Run with: ./forkexec
 
%include        '../functions.asm'
 
SECTION .data
command         db      '/bin/echo', 0h     ; command to execute
arg1            db      'Hello World!', 0h
arguments       dd      command
                dd      arg1                ; arguments to pass to commandline (in this case just one)
                dd      0h                  ; end the struct
environment     dd      0h                  ; arguments to pass as environment variables (inthis case none) end the struct

childMsg        db      'This is the child process', 0h     ; a message string
parentMsg       db      'This is the parent process', 0h    ; a message string

SECTION .bss
status   resb 8 			    ; reserving 8 bytes of memory to store a descriptor
pid 	 resb 8 			    ; storing a pid

SECTION .text
global  _start
 
_start:
 
    mov     eax, 2              ; invoke SYS_FORK (kernel opcode 2)
    int     80h

    cmp    eax, 0   ;checking if fork failed   
    jl     error

    mov     [pid], eax          ; moving return value of fork to pid, so we can use it later

    cmp     eax, 0              ; if eax is zero we are in the child process
    jz      child               ; jump if eax is zero to child label
 
parent:
    mov     eax, parentMsg      ; since we already moved out pid, we can safely move parentMsg to eax
    call    sprintLF            ; calling our sprintLF function that's defined in functions.asm 

    ; invoking waitpid
    mov    eax, 7        ; waitpid is opcode 7
    mov    ebx, [pid]    ; move our pid value to ebx
    mov    ecx, status   ; move the status value we declared to ecx
    mov    edx, 0        ; move options (currently set to 0) to edx
    int    80h
 
   call    quit                ; quit the parent process
 
child:
    mov     eax, childMsg       ; inside our child process move childMsg into eax
    call    sprintLF            ; call our string printing with linefeed function

    mov     edx, environment    ; address of environment variables
    mov     ecx, arguments      ; address of the arguments to pass to the commandline
    mov     ebx, command        ; address of the file to execute
    mov     eax, 11             ; invoke SYS_EXECVE (kernel opcode 11)
    int     80h

    call    quit                ; quit the child process

error:
     mov  ebx, -1    ;return -1 for error
     mov  eax, 1
     int  80h