我是 Linux 编程的新手,我想获得一些关于终止使用 execvp()
启动的进程的建议。以下是将 "TestApplication"
作为子进程启动的代码。当用户中断 (ctrl+C) 时,我想终止 "TestApplication"
以及父进程。
有关如何实现此目标的任何建议。请。帮助。谢谢。
int main(int argc, char* argv[])
{
signal(SIGINT, KillProcess);
pid_t pid;
pid = fork();
if(pid == -1)
{
printf("Error: Fork process failed");
exit(-1);
}
else if (pid == 0)
{
char *const paramList[] = {"5"," 1", NULL};
execvp("TestApplication", paramList);
}
else
{
// Wait for signal from the TestApplication process when successfully executed
}
return 0;
}
void KillProcess(int sig)
{
// Want to get the process ID of "TestApplication"
// Then force Kill it
}
最佳答案
How to get the process ID of process started via execvp() ?
fork()
返回值给父进程启动子进程 PID
。
如果fork()
sys_call 没有失败,则子进程中的pid
变量为0,父进程中的pid
产卵的 child 。所以如果你想知道子进程的pid,你可以查看父进程中fork()
的返回值,它存储在pid
中。为了获得父进程 pid
,您可以调用 getpid()
。
关于c - 如何通过execvp()获取进程启动的进程ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42107070/