c - 如何启动一个进程,获取它的 pid,然后再杀死它?
问题描述
首先,这类似于之前在这里和其他地方提出的问题,但我无法得到任何这些答案。我正在尝试构建的是围绕另一个程序的“包装器”,该程序启动它并返回正在运行的进程的 PID。
稍后,要重新配置某些东西,我必须'kill -9 pid'所说的程序(相信我,没有其他办法,即使'kill pid'也不起作用),重新配置,重新启动其他程序,然后返回PID上游的。
我从任何其他答案中尝试过的都没有接近返回 pid,而不是 system()、popen()、fork(),exec_() 系列中没有任何内容。它们都只返回 0 或负错误,没有返回 pid。getpid() 和 getppid() 没有帮助,它们只是调用程序的 pid,而不是我正在启动的其他程序的 pid。
这也可能与 otherprogram 包含一个 'os_daemon()' 行的事实有关,也就是说,当它启动时,它会做一些事情,并自己守护进程。注意我可以阅读这个其他程序的源代码,但我不能修改它。
无论如何,我想做的是这样的:
int startup() {
int retval;
/* do other stuff */
retval = startsomehow("otherprogram args");
return retval;
}
int reconfigure(int runningpid) {
int retval;
system("kill -9 %d",runningpid); /* this doesn't work as written, but you get the idea of what i'm trying to do */
/* do other stuff */
retval = startsomething("otherprogram args");
return retval;
}
我最接近任何工作的东西是:
system("otherprogram args");
retval = (int)system("ps aux | awk '/otherprogram/ {print $1}' | head -n 1"); //this doesn't correctly parse it into an int and still returns 0 because I'm not reading the output properly, but you get the idea
它相当笨重,但几乎可以工作,awk 打印到命令行,但没有将其作为格式正确的 int 放入代码中,如果我能让这部分工作,我会接受它作为最后的努力,但我更喜欢在不使用 system() 太多的情况下直接返回一个 pid 的东西。
绝对绝对的最后手段是忽略事物的 pid 方面并发出“killall -9 otherprogram”,但有可能我将来可能会以不同的 pid 运行同一程序的 2 个副本,所以我d更喜欢杀死一个而让另一个不理会的能力。
ps,这是我使用 fork() 时测试文件中发生的情况:
int main(int argc, char *argv[])
{
fprintf(stdout,"Start, I am pid = %d\n",getpid());
int foo = (int)fork();
fprintf(stdout,"Forked, pid = %d\n",foo);
if (foo == 0) {
fprintf(stdout,"This is child, my pid = %d\n",getpid());
fprintf(stdout,"This is child, foo = %d\n",foo);
} else {
fprintf(stdout,"This is parent, my pid = %d\n",getpid());
fprintf(stdout,"This is parent, foo = %d\n",foo);
foo = exec("otherprogram","args"); //nb, redacted name
fprintf(stdout,"exec returned = %d\n",foo);
system("ps aux | tail -n 9");
}
}
给出:
Start, I am pid = 367
Forked, pid = 368
This is parent, my pid = 367
This is parent, foo = 368
Forked, pid = 0
This is child, my pid = 368
This is child, foo = 0
329 root [kworker/0:0]
354 root [kworker/u2:0]
366 root [kworker/u2:2]
367 root ./testfoo
368 root [testfoo]
370 nobody otherprogram
371 root sh -c ps aux | tail -n 9
372 root ps aux
373 root tail -n 9
这些结果都没有给出'370',这是我想要的数字
解决方案
推荐阅读
- linux - gdb 核心调试 - 如何在回溯中显示 .so 名称
- cucumber - 带有 Cucumber 自定义报告的 TestNG - 单步执行时间
- android - Flutter :在列表中选择一个选项
- python - 更改为通配符导入后,从模块导入所有功能失败
- python - 字符'ñ'的Python Unicode转换
- image - 如何使用cropImage() 将裁剪后的图像保存到Flutter 中的特定文件夹
- docker - Kubernetes 中的自定义 Gitlab CI Runner 无法连接到 gitlab.com docker repo
- microsoft-graph-api - 无法列出外部连接
- wordpress - localhost 一直指向 live...?
- typescript - 从 Svelte Kit 中的加载函数调用 prisma 客户端