如何 运行 一个 child 进程,并用 C 中的 parent 对其进行操作?

How to run a child process, and act on it with the parent in C?

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

杀死它

经过一些研究,我选择使用 Fork/exec 来创建一个 child 进程。 但是当我执行我的代码时,这两个程序不会同时运行。 我打开浏览器后,在关闭之前什么也做不了。

我的代码看起来像那样

#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); 更改其状态。