用C语言在Linux上获取程序进程(服务和守护进程)

时间:2022-07-31 23:55:49

I'd like to know how one would create an application that starts in the background. I'm currently creating a webserver in C as a little project, both to learn some old C and Linux Socket Programming. But my current concern is:

我想知道如何创建一个在后台启动的应用程序。我目前正在C中创建一个Web服务器作为一个小项目,既学习一些旧的C和Linux套接字编程。但我目前关注的是:

  • How do I get the current process number?
  • 我如何获得当前的流程编号?

I want to get this because when I start the process, I want to display the process number for the user who starts the service.

我想得到这个,因为当我开始这个过程时,我想显示启动服务的用户的进程号。

  • My second problem is, how do I start my application as a Daemon to run in the background?
  • 我的第二个问题是,如何启动我的应用程序作为守护进程在后台运行?

Any references, tutorials and/or videos on how I'd do this is appreciated!

任何有关我如何做到这一点的参考,教程和/或视频表示赞赏!


Maybe I was a little bit unclear; I want to get the Process ID from within C. So, do I need to create a shell script for my application or can I do this from C?

也许我有点不清楚;我想从C中获取进程ID。那么,我是否需要为我的应用程序创建一个shell脚本,或者我可以从C执行此操作吗?

2 个解决方案

#1


  1. To get the running process' identifier, use the getpid() function.
  2. 要获取正在运行的进程的标识符,请使用getpid()函数。

  3. To create a daemon, i.e. a detached process running in the background, follow these instructions.
  4. 要创建守护程序,即在后台运行的分离进程,请按照这些说明操作。

#2


On *nix, get the process id with ps or if you know the process name, do

在* nix上,使用ps获取进程ID,或者如果您知道进程名称,请执行

ps aux | grep processname

And to run any program as a daemon, use nohup

要将任何程序作为守护程序运行,请使用nohup

#1


  1. To get the running process' identifier, use the getpid() function.
  2. 要获取正在运行的进程的标识符,请使用getpid()函数。

  3. To create a daemon, i.e. a detached process running in the background, follow these instructions.
  4. 要创建守护程序,即在后台运行的分离进程,请按照这些说明操作。

#2


On *nix, get the process id with ps or if you know the process name, do

在* nix上,使用ps获取进程ID,或者如果您知道进程名称,请执行

ps aux | grep processname

And to run any program as a daemon, use nohup

要将任何程序作为守护程序运行,请使用nohup