#include<unistd.h> #include<stdio.h> intmain() { pid_t fpid; //fpid表示fork函数返回的值 int count = 0; fpid = fork(); if (fpid < 0) printf("error in fork!\n"); elseif (fpid == 0) { printf("i am the child process, my process id is %d\n", getpid()); printf("我是爹的儿子\n"); count++; } else { printf("i am the parent process, my process id is %d\n", getpid()); printf("我是孩子他爹\n"); count++; } printf("统计结果是: %d\n", count); return0; }
if (fork() == 0){ //child process char * execv_str[] = {"echo", "executed by execv",NULL}; if (execv("/usr/bin/echo",execv_str) <0 ){ perror("error on exec"); exit(0); } }else{ //parent process wait(&childpid); printf("execv done\n\n"); }
execvp 函数
1 2 3 4 5 6 7 8 9 10 11 12
if (fork() == 0){ //child process char * execvp_str[] = {"echo", "executed by execvp",">>", "~/abc.txt",NULL}; if (execvp("echo",execvp_str) <0 ){ perror("error on exec"); exit(0); } }else{ //parent process wait(&childpid); printf("execvp done\n\n"); }
execve 函数
1 2 3 4 5 6 7 8 9 10 11 12 13
if (fork() == 0){ //child process char * execve_str[] = {"env",NULL}; char * env[] = {"PATH=/tmp", "USER=lei", "STATUS=testing", NULL}; if (execve("/usr/bin/env",execve_str,env) <0 ){ perror("error on exec"); exit(0); } }else{ //parent process wait(&childpid); printf("execve done\n\n"); }
execl 函数
1 2 3 4 5 6 7 8 9 10 11
if (fork() == 0){ //child process if (execl("/usr/bin/echo","echo","executed by execl" ,NULL) <0 ){ perror("error on exec"); exit(0); } }else{ //parent process wait(&childpid); printf("execv done\n\n"); }
execlp 函数
1 2 3 4 5 6 7 8 9 10 11
if (fork() == 0){ //child process if (execlp("echo","echo","executed by execlp" ,NULL) <0 ){ perror("error on exec"); exit(0); } }else{ //parent process wait(&childpid); printf("execlp done\n\n"); }
execle 函数
1 2 3 4 5 6 7 8 9 10 11 12
if (fork() == 0){ //child process char * env[] = {"PATH=/home/gateman", "USER=lei", "STATUS=testing", NULL}; if (execle("/usr/bin/env","env",NULL,env) <0){ perror("error on exec"); exit(0); } }else{ //parent process wait(&childpid); printf("execle done\n\n"); }