gpt4 book ai didi

linux - 如何在linux中创建一个进程

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:00:34 25 4
gpt4 key购买 nike

我正在尝试在 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("/usr/bin/firefox","firefox",NULL);

您还需要在 execlp 之后放置一个 _exit,以防它失败。

关于linux - 如何在linux中创建一个进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12831806/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com