fork 和 exec 分离
可知 fork
和 exec
分离,中间过程可以做一些事情。重定向和管道都是在 fork 和 exec 之间做手脚的。
重定向
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
int main(int argc, char *argv[]){
int rc = fork(); // 1 fork
if(rc < 0){
fprintf(stderr, "fork failed\n");
exit(1);
} else if(rc == 0){ // 子进程
close(STDOUT_FILENO); // 关闭默认的 file descriptor
open("./p4.output",O_CREAT|O_WRONLY|O_TRUNC,S_IRWXU); // 新的 fd
char * myargs[3];
myargs[0] = strdup("wc");
myargs[1] = strdup("p4.c");
myargs[2] = NULL;
execvp(myargs[0],myargs); // 2 execvp
} else { // 父进程
int rc_wait = wait(NULL);
}
return 0;
}