2016-09-19 77 views
1

我目前正在嘗試在C程序中將Internet瀏覽器(Firefox)作爲子進程運行,並對其執行操作。起初,我希望得到孩子的pid並與父母一起殺死。如何運行一個子進程,並用C中的父進程對其進行操作?

經過一些研究,我選擇使用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造成的一些故障運行。 我得到這樣的輸出:

[email protected]:/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中/文檔/謨/ git_sources/ProjetSIDA#

回答

1

當瀏覽器打開時,您無法在命令提示符下執行任何操作,因爲這一行代碼。

waitpid(pid, 0, 0); 

如果您將其註釋掉,您可以打開瀏覽器並返回命令提示符重新接受輸入。

原因是你要求你的主進程(a.out在你的情況)等待瀏覽器進程改變其狀態waitpid(pid, 0, 0);