Skip to content
systemcoding.dev
Assembly

Get your process ID with the getpid syscall (39)

Call getpid (39) in GNU as 2.43 and print the result as decimal digits, built backwards with div by 10; the pid differs every run.

1 min read
Summarize in AI

getpid is system call 39 and takes no arguments; the process ID comes back in rax. Turning it into text is the real work, since there is no printf here. The usual method divides by 10 repeatedly, storing each remainder as a digit from the end of a buffer backwards so the digits come out in order. This GNU as 2.43 program prints the PID and a newline.

getpid.sasm
    .bss
buf:    .skip   20
    .data
nl:     .byte   10

    .text
    .globl  _start
_start:
    mov     $39, %eax
    syscall                     /* rax = pid */
    lea     buf+20(%rip), %rdi  /* one past the end */
    mov     $10, %ecx
1:  xor     %edx, %edx
    div     %rcx                /* rax /= 10, rdx = digit */
    add     $48, %dl            /* '0' */
    dec     %rdi
    mov     %dl, (%rdi)
    test    %rax, %rax
    jnz     1b
    lea     buf+20(%rip), %rdx
    sub     %rdi, %rdx          /* digit count */
    mov     %rdi, %rsi
    mov     $1, %edi
    mov     $1, %eax
    syscall
    mov     $1, %edx
    lea     nl(%rip), %rsi
    mov     $1, %eax
    syscall
    xor     %edi, %edi
    mov     $60, %eax
    syscall
Text
$ ./getpid
48213

The number printed will differ on every run, and in a container it may be small. div %rcx divides rdx:rax, so rdx must be zeroed first, which is the xor at the top of the loop. A pid of 0 would print 0, since the loop body runs once before testing. getpid cannot fail, so there is no error path. On Linux 6.12 every call enters the kernel, because getpid has no vDSO shortcut.

Also inKernels
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.