【问题标题】:How to create a process in linux如何在linux中创建一个进程
【发布时间】:2012-10-11 03:36:01
【问题描述】:

我正在尝试在 linux 中创建一个进程,但是我不断收到错误消息。在我的 c++ 代码中,我只想打开 firefox.exe。这是我的代码:

//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);
    }
}

wait() 函数出错。我忽略了这个并尝试了,但没有任何反应。

【问题讨论】:

  • 如果检查 execlp() 是否有错误,然后确保子进程退出,会发生什么?

标签: linux createprocess


【解决方案1】:

你必须写:

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

你还需要在 execlp 之后加上一个 _exit 以防它失败。

【讨论】:

  • 实际上您确实创建了一个进程(因为fork 没有失败),但是,该进程未能运行firefox,因为您的execlp 错误。教训:始终测试每个系统调用是否成功(当它无法通知用户时,您可以使用perror)。
【解决方案2】:

我认为你没有正确调用execlp

它不会将"firefox" 附加到"usr/bin"。因为它会搜索PATH 环境变量,所以您可以使用execlp("firefox","firefox",NULL) 调用它。


旁白: 是的,exec 系列函数允许您打破argv[0] 应该命名可执行文件的名义保证。对不起,就是这样。

【讨论】:

    【解决方案3】:

    要创建一个进程,您可以使用系统调用、fork 调用、execl 调用。 要了解如何使用这些调用在 linux 中创建进程,请点击以下链接。 我认为它将通过示例帮助您更多地了解流程创建。 http://www.firmcodes.com/process-in-linux/

    【讨论】:

      猜你喜欢
      • 2014-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-07
      • 1970-01-01
      • 2011-08-18
      • 1970-01-01
      • 2013-07-31
      相关资源
      最近更新 更多