-1

Probably the core of this question has been asked a lot on this site.

I'mm working with pocketsphinx and I'm trying to play music each time I request it.

When I say "MUSIC" the program executes the music, my idea is that when I say "STOP" music should stop. I'm trying to get the PID the following way. I got this idea from this question

I though using popen I will get the PID, but isn't that way when it get to pid_t pid = strtoul(line, NULL, 10); it's returning me 0.

How I can get this PID and continue with the program running at the same time?

I'm using the same template that you will find on the pocketsphinx want to see it with modifications here: 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);

}
Community
  • 1
  • 1
Diego
  • 916
  • 1
  • 13
  • 36

1 Answers1

1

You can refer the below code to find the PID of a process. Execute with "root" permission

The argument to the executable will the name of the process for which the PID has to obtained

#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;
}

Based on the sizeof the process name vary the length of the command.

Implementation 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;
}

Change YOUR_APP with your application name. Tested with other commands.

Santosh A
  • 5,173
  • 27
  • 37
  • Is there a way to get it with out needing to write on a file? Planning to a recognition voice app and I don't see it as a very good optimization. Let me test it and give it you the accepted answer – Diego Nov 11 '14 at 13:45
  • @Diego: Implemenatation 2 added: optimized one – Santosh A Nov 12 '14 at 04:39