exec
父进程利用fork函数创建子进程以后,子进程往往需要调用一种exec函数,执行的程序完全替换为新程序,而新程序从main函数开始执行,exec函数并不创建新进程,当前进程的ID完全没变,不过以一个全新的程序代替了当前进程的正文,数据空间,堆,栈。
#include  <sys/wait.h>
#include  <errno.h>
#include  <unistd.h>

int system(const char *cmdstring) 
{
  pid_t  pid;
   int    status;

   if (cmdstring == NULL)
     return(1);     /* always a command processor with UNIX */

   if ((pid = fork()) < 0)
  {
    status = -1;   /* probably out of processes */
  }
   else if (pid == 0)
  {      
    execl("/bin/sh", "sh", "-c", cmdstring, ( char *)0);
    _exit(127);     /* execl error */
  }
   else
  {              
     while (waitpid(pid, &status, 0) < 0)
    {
        if (errno != EINTR) {status = -1;   break;}
    }
  }
   return(status);
}
以上只是写在unix系统下中.c文件中的一个函数,下面写个测试system函数的程序
#include "apue.h"
#include <sys/wait.h>

int main(void)
{
  int    status;

   if ((status = system( "date")) < 0)
    err_sys( "system() error");
  pr_exit(status);

   if ((status = system( "nosuchcommand")) < 0)
    err_sys( "system() error");
  pr_exit(status);

   if ((status = system( "who; exit 44")) < 0)
    err_sys( "system() error");
  pr_exit(status);

   exit(0);
}
就可以得到这些命令中程序所应该输出的结果