简体   繁体   中英

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

I'm currently trying to run an Internet browser (Firefox) as a child process in a C program and perform actions on it. At first I'd like to get child's pid and kill it with parent.

After some researches I've chosen to use Fork / exec to create a child process. But when I execute my code, the two programs doesn't run simultaneously. After I opened my browser, I can't do anything before closing it.

My code looks like that

#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;
}

For now I got navigator running with some errors due to Firefox. And I get this kind of output :

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

And this last line when I close iceweasel:

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

You are not able to do anything with your command prompt when your browser is on is because this line of code.

waitpid(pid, 0, 0);

If you comment it out, you can open the browser and get your command prompt back to accept input again.

The reason is your are asking your main process( a.out in your case) to wait for the browser process to change its state with waitpid(pid, 0, 0); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM