2015-03-13 23 views
0

我把示例程序從Advanced Linux Programming網站:分叉和執行程序不會返回到控制檯

/*********************************************************************** 
* Code listing from "Advanced Linux Programming," by CodeSourcery LLC * 
* Copyright (C) 2001 by New Riders Publishing       * 
* See COPYRIGHT for license information.        * 
***********************************************************************/ 

#include <stdio.h> 
#include <stdlib.h> 
#include <sys/types.h> 
#include <unistd.h> 

/* Spawn a child process running a new program. PROGRAM is the name 
    of the program to run; the path will be searched for this program. 
    ARG_LIST is a NULL-terminated list of character strings to be 
    passed as the program's argument list. Returns the process id of 
    the spawned process. */ 

int spawn (char* program, char** arg_list) 
{ 
    pid_t child_pid; 

    /* Duplicate this process. */ 
    child_pid = fork(); 
    if (child_pid != 0) 
    /* This is the parent process. */ 
    return child_pid; 
    else { 
    /* Now execute PROGRAM, searching for it in the path. */ 
    execvp (program, arg_list); 
    /* The execvp function returns only if an error occurs. */ 
    fprintf (stderr, "an error occurred in execvp\n"); 
    abort(); 
    } 
} 

int main() 
{ 
    /* The argument list to pass to the "ls" command. */ 
    char* arg_list[] = { 
    "ls",  /* argv[0], the name of the program. */ 
    "-l", 
    "/", 
    NULL  /* The argument list must end with a NULL. */ 
    }; 

    /* Spawn a child process running the "ls" command. Ignore the 
    returned child process id. */ 
    spawn ("ls", arg_list); 

    printf ("done with main program\n"); 

    return 0; 
} 

編譯和從控制檯運行它之後,子進程不會退出,因此不會釋放安慰。

只有Ctrl + C有助於返回控制檯。

[email protected] ~/Projects/test $ gcc -o test test.c 
[email protected] ~/Projects/test $ ./test 
done with main program 
[email protected] ~/Projects/test $ total 104 
drwxr-xr-x 2 root root 4096 Mar 11 11:57 bin 
drwxr-xr-x 3 root root 4096 Mar 11 11:57 boot 
[ ... too many lines of my filesystem skipped ... ] 
drwxr-xr-x 10 root root 4096 Nov 27 01:12 usr 
drwxr-xr-x 11 root root 4096 Nov 27 01:48 var 
^C 
[email protected] ~/Projects/test $ 

如何運行另一程序並退出到控制檯?

回答

2

完成第一個程序,無需等待子進程完成。 shell給你一個提示,但是然後ls -l命令的輸出開始了。

當你點擊中斷時shell仍在等待你;如果您輸入echo Hi,它會完成您的出價。

這是你的樣本輸出,註釋:

[email protected] ~/Projects/test $ gcc -o test test.c 
[email protected] ~/Projects/test $ ./test 
done with main program 
[email protected] ~/Projects/test $ total 104 

前一行有你的提示,並且還輸出從ls -l第一線。

drwxr-xr-x 2 root root 4096 Mar 11 11:57 bin 
drwxr-xr-x 3 root root 4096 Mar 11 11:57 boot 
[ ... too many lines of my filesystem skipped ... ] 
drwxr-xr-x 10 root root 4096 Nov 27 01:12 usr 
drwxr-xr-x 11 root root 4096 Nov 27 01:48 var 
^C 

如果你輸入的echo Hi代替控制-C,你會看到Hi和下一個提示。就像您在中斷外殼後得到下一個提示...

[email protected] ~/Projects/test $ 
相關問題