Natasha Nieves
Natasha Nieves

Reputation: 3

Getting process id without library functions?

Hi I know how to get the pid using c++ using library function getpid() is there anyway to do this without calling a library function?

Upvotes: 0

Views: 1008

Answers (2)

Brandon
Brandon

Reputation: 23495

For my windows buddies out there..

#include <cstdio>
#include <windows.h>

int getPID()
{
    #ifndef _MSC_VER
        #ifndef __x86_64__
        asm ("movl %%FS:0x20, %%eax":::);
        #else
        asm ("movq %%GS:0x40, %%rax":::);
        #endif
    #else
        #ifndef _WIN64
        __asm {mov eax, FS:[0x20];};
        #else
        __asm {mov rax, GS[0x40];};
        #endif
    #endif
}

int main()
{
    printf("%d\n", getPID());
    printf("%d", GetCurrentProcessId());
}

Upvotes: 0

Galik
Galik

Reputation: 48635

If you're after syscall then there is this:

http://man7.org/linux/man-pages/man2/syscall.2.html

#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h>

int main()
{
    pid_t pid = syscall(SYS_getpid);

    std::cout << pid << '\n';
}

Upvotes: 1

Related Questions