c - 如何跟踪 C Linux 中 system() 运行的后台进程?

标签 c node.js linux

我正在从我的 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/

相关文章:

c - 如何为 mmap() 禁用写时复制和按需填零

node.js - npm 包列表中删除了哪些内容?

linux - 比较 boolean 变量以检查互联网连接

c - 在 C 中使用宏将项目附加到数组

c - 将多个 C 库链接到 C 创建可执行文件

c - 从文件中以不同的字符串读取 2 个巨大的数字

javascript - 两端都可以理解通过用不同语言编写的套接字发送/接收的数据吗?

javascript - mysql timestamp now()不适用于nodejs

php - 使用 PHP 控制用户输入的 Javascript/HTML/textarea 并防止 iframe hack

linux - Rhapsody 可以配置为使用外部源代码编辑器吗?