我正在从我的 C 应用程序在后台启动一个 Node 应用程序。但是,我想跟踪 Node 是否正在运行。就像,我想继续监视 Node 是否正在运行。如果不是,那么我想启动它。
如何做到这一点,有什么方法可以在后台运行时从 system() 调用中获取 Node 的 pid?另外,是否有任何 API 可以知道 Node 是否正在运行? 这是我的系统 API。
*
int nodeCmd (const char *command)
{
int status;
pid_t pid;
pid = fork ();
if (pid == 0)
{
/* This is the child process. Execute the shell command. */
execl (SHELL, SHELL, "-c", command, NULL);
_exit (EXIT_FAILURE);
}
else if (pid < 0)
{
/* The fork failed. Report failure. */
status = -1;
}
else
{
/* This is the parent process. Wait for the child to complete. */
if (waitpid (pid, &status, 0) != pid)
status = -1;
}
return status;
}
void main()
{
snprintf(command, sizeof(command), "/usr/local/bin/node &");
nodeCmd(command);
}
*
最佳答案
我定期运行这个函数来检查进程是否正在运行。这是我的函数,它将检查 linux,C 中的运行进程。
static int CheckRunningStatus(void)
{
FILE *fp = NULL;
char nodePidCheck[16];
int ret = 0;
memset(nodePid,0,16);
/* Open the command for reading. */
fp = popen("pidof node", "r");
if (fp == NULL)
{
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - pid of node will be just 1 line*/
// if there is no PID then nothing will be poplated inside nodePid
fgets(nodePid, sizeof(nodePid)-1, fp);
// check if we have got a PID value of node or not
if(nodePid[0] == 0)
{
printf("node is not running!!!!\n");
ret = -1;
}
/* close the popen handle */
pclose(fp);
return ret;
}
关于c - 如何跟踪 C Linux 中 system() 运行的后台进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48847628/