c - 如何通过execvp()获取进程启动的进程ID

标签 c linux

我是 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/

相关文章:

linux - 如何修复此 Bash 函数以从指定路径开始并递归列出其子目录以及这些目录的子目录等

Linux 堆栈大小

c - 搜索目录中的所有子目录

c - 尝试创建一个处理 SIGUSR1 的程序,子进程应该执行另一个可执行文件

客户端通过套接字与服务器进行通信

linux 磁盘利用率冲突

c++ - 线程 0x7fffc57fa700 (LWP 31671) exited] 在 gdb 中是什么意思?

c - `while (1)` 的替代品以简化分支

c++ - gcc 和 g++ 库搜索路径

php - 提供从 Python 脚本到 PHP 的反馈