简体   繁体   中英

C++ getpid() vs syscall(39)?

I read that syscall(39) returns the current process id (pid)

Then why these 2 programs output 2 different numbers?

int main() {
    long r = syscall(39);
    printf("returned %ld\n", r);
    return 0;
}

and:

int main() {
    long r = getpid();
    printf("returned %ld\n", r);
    return 0;
}

I am running my program in clion, and when I change the first line I get different result which is really strange.

Running the code in the answers I got (in macos):

returned getpid()=9390 vs. syscall(39)=8340

which is really strange.

In ubuntu I got same pid for both, why is that?

Making system calls by their number is not going to be portable.

Indeed, we see that 39 is getpid on Linux, but getppid ("get parent pid") on macOS.

getpid on macOS is 20.

So that's why you see a different result between getpid() and syscall(39) on macOS.

Note that macOS, being a BSD kernel derivative, is not related to Linux in any way. It can't possibly be, since it's closed-source.

There's one key detail that's missing here -- every time you run the program, your OS assigns it a new PID. Calling the same program twice in a row will likely return different PIDs - so what you're describing isn't a good way to test the difference between getpid() and syscall(39) .

Here's a better program to compare the two that calls both functions in the same program.

#include <sys/syscall.h>
#include <stdio.h>

int main() {
    long pid1 = getpid();
    long pid2 = syscall(39);
    printf("returned getpid()=%ld vs. syscall(39)=%ld\n", pid1, pid2);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM