【问题标题】:Getting pid trying to stop a program with C让 pid 试图用 C 停止程序
【发布时间】:2014-11-11 05:41:56
【问题描述】:

这个问题的核心可能在这个网站上被问了很多。

我正在使用pocketsphinx,每次我请求它时我都会尝试播放音乐。

当我说“MUSIC”时,程序会执行音乐,我的想法是当我说“STOP”时,音乐应该停止。我正在尝试通过以下方式获取 PID。我从这个question得到这个想法

我虽然使用 popen 我会得到 PID,但是当它到达 pid_t pid = strtoul(line, NULL, 10); 时不是这样,它返回给我 0。

如何获得这个 PID 并继续同时运行程序?

我使用的模板与您在 pocketsphinx 上找到的模板相同,希望在这里看到它的修改:http://pastebin.com/Duu2nbCA

if(strcmp(word, "MUSIC") == 0)
{
    FILE *fpipe;
  char *command = (char *)"aplay BobMarley.wav";
  char line[256];

  if ( !(fpipe = (FILE*)popen(command,"r")) )
  {  // If fpipe is NULL
    perror("Problems with pipe");
    exit(1);
  }
  fgets( line, sizeof line, fpipe);                 
  pid_t pid = strtoul(line, NULL, 10);
  printf("The id is %d\n", pid);

}

【问题讨论】:

  • 在您的链接问题中,接受的答案是在pidof 上执行popen。那不是你在做什么。你基本上需要做两次popen,第一次是aplay,第二次是pidof
  • @Diego 你试过用root permission 执行你的程序吗?
  • @DoxyLover 我如何获得 pidof aplay?

标签: c linux voice-recognition


【解决方案1】:

您可以参考以下代码来查找进程的 PID。以"root" 权限执行

可执行文件的参数将是必须为其获取 PID 的进程的名称

#define TMP_FILE  "/tmp/pid"

int main(int argc, char** argv)
{
    FILE *fpipe;
    int pid = 0;
    char command[50] = "pidof -s ";

    if (argc != 2) {
        printf("Invalid input\n");
        return -1;
    }

    strcat(command, argv[1]);
    strcat(command, " > "TMP_FILE);
    system(command);

    fpipe = fopen(TMP_FILE, "r");
    fscanf(fpipe, "%d", &pid);
    printf("The pid is %d\n", pid);
    fclose(fpipe);

    return 0;
}

根据进程名的大小改变命令的长度。

实施 2

int main( int argc, char *argv[] )
{

    FILE *fp;
    char path[10];

    fp = popen("/sbin/pidof -s YOUR_APP", "r");
    if (fp == NULL) {
        printf("Failed to run command\n" );
        exit(1);
    }

    /* Read the output a line at a time - output it. */
    while (fgets(path, sizeof(path), fp) != NULL) {
        printf("%s", path);
    }


    pclose(fp);

    return 0;
}

YOUR_APP 更改为您的应用程序名称。 用其他命令测试。

【讨论】:

  • 有没有办法在不需要写入文件的情况下获得它?计划一个识别语音应用程序,我不认为这是一个很好的优化。让我测试一下,然后给你接受的答案
  • @Diego:添加实现 2:优化一个
猜你喜欢
  • 2012-08-14
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-10
  • 1970-01-01
相关资源
最近更新 更多