Chinaunix首页 | 论坛 | 博客
  • 博客访问: 172329
  • 博文数量: 37
  • 博客积分: 1690
  • 博客等级: 上尉
  • 技术积分: 468
  • 用 户 组: 普通用户
  • 注册时间: 2010-09-13 21:30
文章分类

全部博文(37)

文章存档

2011年(19)

2010年(18)

我的朋友

分类:

2011-05-09 14:30:33

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

    if(cmdstring == NULL){
          
         return (1);
    }


    if((pid = fork())<0){

            status = -1;
    }
    else if(pid == 0){
        execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
        -exit(127); //子进程正常执行则不会执行此语句
        }
    else{
            while(waitpid(pid, &status, 0) < 0){
                if(errno != EINTER){
                    status = -1;
                    break;
                }
            }
        }
        return status;
}
以上是system函数的源码,它会新起一个子进程调用要执行的文件或命令,而exec函数则会进程直接执行要执行的命令或文件,所以exec后面的代码不会被执行。

execl("/bin/ps", "ps", "-o", "pid,ppid,pgrp,session,tpgid,comm", NULL);
printf(stdout, "sleep over******************\n");
后面这个printf打印语句无效。

而改成system后:
system("ps -o pid,ppid,pgrp,session,tpgid,comm");
printf(stdout, "sleep over******************\n");
则会执行printf语句。

当进程调用一种e x e c函数时,该进程完全由新程序代换,而新程序则从其m a i n函数开始执行
阅读(1337) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~