进程控制:
fork创建一个新的进程,该进程为调用进程的复制。
fork向父进程返回该进程的pid,向子进程返回0。
因此新进程被调用一次,但是返回了两次。
/*************************************************************************
> File Name: test1-4.c
> Author: team79
> Mail: huzihao79@163.com
> Created Time: 2017年08月25日 星期五 11时13分39秒
************************************************************************/
#include "apue.h"
#include <sys/wait.h>
int main(){
char buf[MAXLINE];
pid_t pid;
int status;
//printf("%d %%\n",getpid());
printf("%% ");
while(fgets(buf,MAXLINE,stdin)!=NULL){
if(buf[strlen(buf)-1]=='\n'){
buf[strlen(buf)-1] = 0;
}
if((pid=fork())<0){
err_sys("fork error");
}else if(pid == 0){
printf("pid:%d\n",getpid());
execlp( buf, buf, (char *)0);
err_ret("couldn't execute :%s",buf);
exit(127);
}
//printf("pid:%d\n",getpid());
if((pid=waitpid(pid,&status,0))<0){
err_sys("wait pid error");
}
//printf("pid:%d\n",getpid());
printf("%% ");//如果没有 从err_ret 到上面的err_sys的代码,子进程会一直执行到这一句之后返回,不知道为什么。。。。。
}
exit(0);
}
输出:
hzh@hzh-computer:~/MyUnixRoad$ gcc test1-4.c
hzh@hzh-computer:~/MyUnixRoad$ ./a.out
% date
pid:3028
2017年 08月 25日 星期五 20:30:24 CST
% who
pid:3029
hzh :0 2017-08-25 19:14 (:0)
hzh pts/0 2017-08-25 19:16 (:0)