سؤال

I'm trying to create a process in linux, however I keep getting an error. In my c++ code, I just want to open firefox.exe. Here's my code:

//header files
#include <sys/types.h> 
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <iostream>

using namespace std;

//main function used to run program
int main()
{
    //declaration of a process id variable
    pid_t pid;

    //fork a child process is assigned 
    //to the process id
    pid=fork();

    //code to show that the fork failed
    //if the process id is less than 0
    if(pid<0)
    {
        fprintf(stderr, "Fork Failed");// error occurred
        exit(-1); //exit
    }

    //code that runs if the process id equals 0
    //(a successful for was assigned
    else if(pid==0)
    {
        //this statement creates a specified child process
        execlp("usr/bin","firefox",NULL);//child process
    }

    //code that exits only once a child 
    //process has been completed
    else
    {
        wait(NULL);//parent will wait for the child process to complete
        cout << pid << endl;

        printf("Child Complete");
        exit(0);
    }
}

There is an error for the wait() function. I left this out and tried, but nothing happened.

هل كانت مفيدة؟

المحلول

You have to write:

execlp("/usr/bin/firefox","firefox",NULL);

You also need to put an _exit after execlp in case it fails.

نصائح أخرى

I don't think that you have called execlp correctly.

It isn't going to append "firefox" to "usr/bin". Because it will search the PATH environment variable you can call it with execlp("firefox","firefox",NULL).


Aside: Yes, the exec family of functions allows you to break the nominal guarantee that argv[0] should name the executable. Sorry, that is just the way it is.

To create a process you can use system call, fork call, execl call. TO know how to create process in linux using these call please follow the following link. I think it will help you more to understand about process creations with example. http://www.firmcodes.com/process-in-linux/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top