Get PID of process after fork in Qt

試著忘記壹切 提交于 2019-12-02 03:17:08
Albert

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

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.

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.

Anyway:

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

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.

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() 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().

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!