Linux学习笔记--fork

进程控制:
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
20170825日 星期五 20:30:24 CST
% who
pid:3029
hzh      :0           2017-08-25 19:14 (:0)
hzh      pts/0        2017-08-25 19:16 (:0)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值