linux fork and exec function

System call:

 

http://topic.csdn.net/u/20091208/00/13579016-9085-4b12-8b15-70dacd59cac1.html

 

 

exec()

 

http://blog.chinaunix.net/u3/94667/showart_2100106.html

 

fork()

 

http://blog.chinaunix.net/u/16292/showart_392816.html

 

 

Example from book: Unix环境高级编程

 

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define MAXLINENUM 80

int main(){
    char cmdline[MAXLINENUM];
    pid_t pid;
    int status;
   
    //print prompt
    printf("%%");
   
    while(fgets(cmdline,MAXLINENUM,stdin) != NULL){
        cmdline[strlen(cmdline) - 1 ]=0;
        printf("command line :%s/n",cmdline);
       
        if( (pid = fork()) < 0){
            printf("fork error,exit 1/n");
            return 1;
        }else if(pid == 0){
            execlp(cmdline,(char *) 0);
            printf("Could not execute this command:%s/n",cmdline);
            return 127;
        }
        //else{
        //    wait(&pid);
        //    printf("child process id:%s");
        //}
       
        if((pid = waitpid(pid,&status,0)) < 0){
            printf("waitpid error/n");
        }
        //pause();
        printf("%%");
    }
    return 0;
}

 

 

 

fork的例子函数的输出结果以及原因:摘自《unix环境高级编程》8:进程控制

 

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int glob=87;
char buf[] = "a write to standout.";

int main(){
    int var;
    pid_t pid;   
    var = 100;
   
    if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1)
            printf("write error./n");
   
    printf("/nBefore fork./n");
   
    if((pid=fork()) < 0){
        printf("Error when fork./n");
        return 2;
    }else if(pid == 0){
        var++;
        glob++;
    }else{
        sleep(2);
    }
   
    printf("Pid:%d, global:%d, var:%d, buffer:%s/n",getpid(),glob,var,buf);
    return 1;   
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值