简体   繁体   English

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

[英]C++ getpid() vs syscall(39)?

I read that syscall(39) returns the current process id (pid)我读到 syscall(39) 返回当前进程 id (pid)

Then why these 2 programs output 2 different numbers?那为什么这 2 个程序 output 2 个不同的数字呢?

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.我在 clion 中运行我的程序,当我更改第一行时,我得到了不同的结果,这真的很奇怪。

Running the code in the answers I got (in macos):在我得到的答案中运行代码(在 macos 中):

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

which is really strange.这真的很奇怪。

In ubuntu I got same pid for both, why is that?在 ubuntu 中我得到了相同的 pid,这是为什么呢?

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.事实上,我们看到 39 在 Linux 上是getpid ,但在 macOS 上是getppid (“get parent pid”)。

getpid on macOS is 20. macOS 上的getpid是 20。

So that's why you see a different result between getpid() and syscall(39) on macOS.这就是为什么您在 macOS 上看到getpid()syscall(39)之间结果不同的原因。

Note that macOS, being a BSD kernel derivative, is not related to Linux in any way.请注意,作为 BSD kernel 衍生品的 macOS 与 Linux 没有任何关系。 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.这里缺少一个关键细节——每次运行程序时,操作系统都会为其分配一个新的 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) .连续两次调用同一个程序可能会返回不同的 PID - 所以你所描述的并不是测试getpid()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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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