gpt4 book ai didi

c - 如何运行子进程,并在 C 中与父进程一起操作?

转载 作者:太空宇宙 更新时间:2023-11-04 03:28:17 25 4
gpt4 key购买 nike

我目前正在尝试将 Internet 浏览器 (Firefox) 作为 C 程序中的子进程运行并对其执行操作。起初我想得到 child 的 pid 并用 parent 杀死它。

经过一些研究,我选择使用 Fork/exec 来创建子进程。但是当我执行我的代码时,这两个程序不会同时运行。我打开浏览器后,在关闭之前无法执行任何操作。

我的代码是这样的

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{

//version fork
pid_t pid;
char *parmList[] = {"firefox", "google.com", NULL};
int a;
printf("test001");
if ((pid = fork()) == -1)
perror("fork failed");

if (pid == 0) {
printf("test002");
a = execvp("/usr/bin/firefox", parmList);
printf("test003");
}
else {
waitpid(pid, 0, 0);
printf("test004");
}
return 0;
}

现在,由于 Firefox,我的导航器运行时出现了一些错误。我得到了这种输出:

root@debian:/home/user/Documents/Projet/git_sources/ProjetSIDA# ./a.out

(process:3858): GLib-CRITICAL **: g_slice_set_config: assertion 'sys_page_size == 0' failed
Gtk-Message: Failed to load module "canberra-gtk-module"
console.error:
[CustomizableUI]
Custom widget with id loop-button does not return a valid node
console.error:
[CustomizableUI]
Custom widget with id loop-button does not return a valid node

当我关闭 iceweasel 时,这是最后一行:

test001test004root@debian:/home/user/Documents/Projet/git_sources/ProjetSIDA#

最佳答案

当您的浏览器打开时,您无法使用命令提示符执行任何操作,因为这行代码。

waitpid(pid, 0, 0);

如果您将其注释掉,您可以打开浏览器并返回命令提示符以再次接受输入。

原因是您要求主进程(在您的情况下为 a.out)等待浏览器进程使用 waitpid(pid, 0, 0); 更改其状态;

关于c - 如何运行子进程,并在 C 中与父进程一起操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39567996/

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