在Qt中分叉后获取进程的PID [英] Get PID of process after fork in Qt

查看:786
本文介绍了在Qt中分叉后获取进程的PID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个成功分叉的Qt/C ++控制台应用程序.当我在派生之前调用QCoreApplication :: applicationPid(),然后在派生之后(在子对象中)调用QCoreApplication :: applicationPid()时,我得到了相同的pid.

I am creating a Qt/C++ console application which successfully forks. When I call QCoreApplication::applicationPid() before fork, and then after fork (in the child), I get the same pid.

我意识到我可以使用fork()的返回值,但是我正在尝试以Qt方式进行操作.是否有更好/正确的方法来获取Qt中孩子的PID(从孩子内部)?

I realize I could just use the return value from fork() but I'm trying to do things the Qt way. Is there a better/right way to get the PID of the child (from within the child) in Qt?

出于好奇,为什么QCoreApplication :: applicationPid()不提供新的PID?我认为它现在正在提供ppid....

And out of curiosity, why isn't QCoreApplication::applicationPid() providing the new PID? I assume it's now providing the ppid....

推荐答案

fork()的返回值取决于您是在派生叉中还是在父叉中.请参见此处:

The return value of fork() depends whether you are in the fork or in the parent. See here:

成功后,子进程的PID将在父级中返回,而0将在子级中返回.失败时,将在父级中返回-1,不创建任何子进程,并适当地设置errno.

On success, the PID of the child process is returned in the parent, and 0 is returned in the child. On failure, -1 is returned in the parent, no child process is created, and errno is set appropriately.

因此,您只能从fork()的父对象中获取孩子的pid(似乎并不暗示在孩子中).实际上,这就是您检查自己是否在孩子中的方式,即返回值是否为0.

Thus, you get the pid of the child only within the parent from fork() (not in the child as you seem to imply). That is actually how you check whether you are in the child or not -- i.e. whether the return value is 0 or not.

无论如何:

无法使用fork Qt方法,因为不可能在所有平台(尤其是Windows)上进行分叉,因此Qt无法做到这一点.

There is no way to fork the Qt way because forking is not possible on all platforms (esp. Windows), thus Qt cannot have that.

还请注意,Qt的某些部分在子级中可能处于无效状态(例如,在MacOSX上,Cocoa GUI不能在分支过程中使用).所以要小心.

Also note that certain parts of Qt might be in an invalid state in the child (e.g. on MacOSX, the Cocoa GUI cannot be used in a forked process). So be careful.

我还没有真正找到Qt是否支持fork的细节(我的意思是它表现得很合理:例如,fork中的线程列表会有所不同,因此必须意识到这一点).我已经在此处问过.

I haven't really found details whether Qt otherwise supports forks (I mean in a way that it behaves sane: e.g. the list of threads in the fork will be different, so it must be aware of that). I have asked about that here.

QCoreApplication::applicationPid()可能会缓存该值,从而在子级中返回错误的值.但是不必担心,只需使用getpid()即可-您已经在使用非跨平台的fork().

QCoreApplication::applicationPid() probably caches the value and thus returns the wrong value in the child. But don't care about that, just use getpid() instead -- you are already using the non-cross-platform fork().

这篇关于在Qt中分叉后获取进程的PID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆