linux fork and exec function

来源:互联网 发布:自学java 知乎 编辑:程序博客网 时间:2024/06/12 00:49

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;   
}

 

 

原创粉丝点击