分叉并执行的程序不会 returns 到控制台

Forked and executed program does not returns to console

我从 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 有助于 return 控制台。

vladon@vladon-dev-mint64 ~/Projects/test $ gcc -o test test.c
vladon@vladon-dev-mint64 ~/Projects/test $ ./test
done with main program
vladon@vladon-dev-mint64 ~/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
vladon@vladon-dev-mint64 ~/Projects/test $ 

如何 运行 另一个程序并退出到控制台?

第一个程序完成,没有等待子进程完成。 shell 给了你一个提示,但是 ls -l 命令的输出开始了。

当你打中断时,shell还在等你;如果你输入 echo Hi,它就会完成你的命令。

这是您的样本输出,注释:

vladon@vladon-dev-mint64 ~/Projects/test $ gcc -o test test.c
vladon@vladon-dev-mint64 ~/Projects/test $ ./test
done with main program
vladon@vladon-dev-mint64 ~/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 而不是 Control-C,您会看到 Hi 和下一个提示。就像打断 shell…

后得到下一个提示一样
vladon@vladon-dev-mint64 ~/Projects/test $