You are not logged in.

#1 2008-03-17 20:02:03

High|ander
Member
From: Skövde, Sweden
Registered: 2005-10-28
Posts: 188
Website

C and fork()

Hi

I'm trying to create a simple C program that creates a new process and executes mpg123 in it.
The problem is that the mp3-file is never played.

The code:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main (int argc, char **argv)
{
    int status;
    pid_t pid = fork();

    if (pid < 0 ){
        printf("Fork failed\n");
    }
    else if (pid == 0) {
        execl("mpg123", "file.mp3");
        printf("Lets play\n");
    }
    else {
        printf("Trying to play something\n");
        /* This is the parent process.  Wait for the child to complete.  */
             if (waitpid (pid, &status, 0) != pid) {
             status = -1;
         }
    }
    return 0;
}

Can you see any errors that I have made?

Thanks !


When death smiles at you, all you can do is smile back!
Blog

Offline

#2 2008-03-17 20:09:48

Cerebral
Forum Fellow
From: Waterloo, ON, CA
Registered: 2005-04-08
Posts: 3,108
Website

Re: C and fork()

Do you see "Lets play" appear on the console when you run this?

execl man page wrote:

RETURN VALUE
       If any of the exec() functions returns, an error  will  have  occurred.
       The  return  value  is -1, and the global variable errno will be set to
       indicate the error.

Check the return value of your execl call as well.

Last edited by Cerebral (2008-03-17 20:10:25)

Offline

#3 2008-03-17 20:12:54

Shaika-Dzari
Member
From: Québec, Canada
Registered: 2006-04-14
Posts: 436
Website

Re: C and fork()

Hello!

Try to write the full path to mpg123.
arg0 must be the program name and other argument (file.mp3 for you).

execl("/usr/bin/mpg123","mpg123", "file.mp3");

@+

Last edited by Shaika-Dzari (2008-03-17 20:18:00)

Offline

#4 2008-03-17 22:23:34

High|ander
Member
From: Skövde, Sweden
Registered: 2005-10-28
Posts: 188
Website

Re: C and fork()

Shaika-Dzari wrote:

Hello!

execl("/usr/bin/mpg123","mpg123", "file.mp3");

@+

Changed to your code, and it worked, thanks.

After reading the API doc on execl() I saw my mistake.


When death smiles at you, all you can do is smile back!
Blog

Offline

#5 2008-03-28 17:26:19

srimalik
Member
Registered: 2007-09-16
Posts: 65

Re: C and fork()

Instead of using full path, you can use the execlp function it will search the executable in the PATH environment variable.

-Sri

Offline

Board footer

Powered by FluxBB